实验2

任务一

源代码

点击查看代码
t.h
#pragma once
#include <string>
class T {
public:
T(int x = 0, int y = 0); 
T(const T &t); 
T(T &&t); 
~T();
void adjust(int ratio); 
static int get_cnt(); 
friend void output(const T &t); 
static const std::string doc; 
static const int MAX_CNT; 
private:
int m1, m2; 
static int current_cnt; 
};

t.cpp
#include "t.h"
#include <iostream>
#include <stdexcept>
#include <string>
const std::string T::doc{"a simple class sample"};
const int T::MAX_CNT = 999;
int T::current_cnt = 0;
T::T(int x, int y): m1{x}, m2{y} {
if(current_cnt == MAX_CNT) {
throw std::runtime_error("T: maximum object count exceeded");
}
++current_cnt;
std::cout << "T constructor called.\n";
}
T::T(const T &t): m1{t.m1}, m2{t.m2} {
if(current_cnt == MAX_CNT) {
throw std::runtime_error("T: maximum object count exceeded");
}
++current_cnt;
std::cout << "T copy constructor called.\n";
}
T::T(T &&t): m1{t.m1}, m2{t.m2} {
if(current_cnt == MAX_CNT) {
throw std::runtime_error("T: maximum object count exceeded");
}
++current_cnt;
std::cout << "T move constructor called.\n";
}
T::~T() {
--current_cnt;
std::cout << "T destructor called.\n";
}
void T::adjust(int ratio) {
m1 *= ratio;
m2 *= ratio;
}
int T::get_cnt() {
return current_cnt;
}
void output(const T &t) {
std::cout << "(" << t.m1 << ", " << t.m2 << ")";
}

task1.cpp
#include <iostream>
#include <utility>
#include "t.h"
void test() {
using std::cout;
using std::endl;
cout << "T info: " << T::doc << endl;
cout << "T objects'max count: " << T::MAX_CNT << endl;
cout << "T objects'current count: " << T::get_cnt() << endl << endl;
{
T t1;
cout << "t1 = "; output(t1); cout << endl;
T t2(3, 4);
cout << "t2 = "; output(t2); cout << endl;
T t3(t2);
t3.adjust(2);
cout << "t3 = "; output(t3); cout << endl;
T t4(std::move(t2));
cout << "t4 = "; output(t4); cout << endl;
cout << "test: T objects'current count: " << T::get_cnt() << endl;
}
cout << "test: T objects'current count: " << T::get_cnt() << endl;
}
int main() {
std::cout << "test Class T: \n";
test();
}

运行结果截图

image

问题与讨论

问题1
1.line7普通构造函数:创建新成员,初始化变量,调用时机是创建该类的对象。
2.line8复制构造函数:把已有对象的数据成员复制给新对象,调用时机是初始化新对象时。
3.line9移动构造函数:将临时对象的资源转移给新对象,调用时机是初始化新对象。
4.line10析构函数:对象销毁前释放资源,对象离开作用域时自动调用
T t1:普通构造,T t2:普通构造,T t3(t2):拷贝构造函数,T t4(std::move(t2)):移动构造函数。
问题2
放在头文件里,每个包含它的源文件都会生成一份定义,触发多重定义(multiple definition)链接错误。类内 static 只是声明,定义只能放在 cpp 源文件,全局仅一份。
问题3
t1,t2,t3,t4定义在一对{ }内部,属于块作用域;生命周期从定义语句开始,到}结束,出这个大括号就销毁。不能通过t1访问,体现封装的特性。
问题4
程序崩溃了,ai给出答案:已经创建成功的 t1、t2 会正常销毁
理由:C++ 栈展开(stack unwinding)机制:抛出异常、栈回退时,在抛出点之前已经构造完成的局部对象,会自动调用析构函数销毁,然后再终止程序。

任务二

源代码

点击查看代码
Complex.h
```plaintext
#ifndef COMPLEX_H
#define COMPLEX_H
#include <string>
class Complex
{
public:
    static const std::string doc;
    Complex();
    Complex(double r);
    Complex(double r, double i);
    Complex(const Complex& other);
    double real() const;
    double imag() const;
    void add(const Complex& other);
    friend void output(const Complex& c);
    friend double abs(const Complex& c);
    friend Complex add(const Complex& a, const Complex& b);
    friend bool is_equal(const Complex& a, const Complex& b);
    friend bool is_not_equal(const Complex& a, const Complex& b);
private:
    double real_;
    double imag_;
};
#endif
Complex.cpp
```plaintext
#include "Complex.h"
#include <iostream>
#include <cmath>
const std::string Complex::doc = "a simplified Complex class";
Complex::Complex() : real_(0), imag_(0) {}
Complex::Complex(double r) : real_(r), imag_(0) {}
Complex::Complex(double r, double i) : real_(r), imag_(i) {}
Complex::Complex(const Complex& other) : real_(other.real_), imag_(other.imag_) {}
double Complex::real() const
{
    return real_;
}
double Complex::imag() const
{
    return imag_;
}
void Complex::add(const Complex& other)
{
    real_ += other.real_;
    imag_ += other.imag_;
}
void output(const Complex& c)
{
    if(c.imag_ >= 0)
    {
        std::cout << c.real_ << " + " << c.imag_ << "i";
    }
    else
    {
        std::cout << c.real_ << " - " << -c.imag_ << "i";
    }
}
double abs(const Complex& c)
{
    return sqrt(c.real_ * c.real_ + c.imag_ * c.imag_);
}
Complex add(const Complex& a, const Complex& b)
{
    return Complex(a.real_ + b.real_, a.imag_ + b.imag_);
}
bool is_equal(const Complex& a, const Complex& b)
{
    return a.real_ == b.real_ && a.imag_ == b.imag_;
}
bool is_not_equal(const Complex& a, const Complex& b)
{
    return !(a.real_ == b.real_ && a.imag_ == b.imag_);
}
task2.cpp
```plaintext
#include <iomanip>
#include <iostream>
#include <complex>
#include "Complex.h"
using std::cout;
using std::endl;
using std::boolalpha;
void test_Complex()
{
    cout << "类成员测试: " << endl;
    cout << Complex::doc << endl << endl;
    cout << "Complex对象测试: " << endl;
    Complex c1;
    Complex c2(3, -4);
    Complex c3(c2);
    Complex c4 = c2;
    const Complex c5(3.5);
    const Complex c6 = 3.5;
    cout << "c1 = "; output(c1); cout << endl;
    cout << "c2 = "; output(c2); cout << endl;
    cout << "c3 = "; output(c3); cout << endl;
    cout << "c4 = "; output(c4); cout << endl;
    cout << "c5 = "; output(c5); cout << endl;
    cout << "c6.real = " << c6.real()
         << ", c6.imag = " << c6.imag() << endl << endl;
    cout << "复数运算测试: " << endl;
    cout << "abs(c2) = " << abs(c2) << endl;
    c1.add(c2);
    cout << "c1 += c2, c1 = "; output(c1); cout << endl;
    cout << boolalpha;
    cout << "c1 == c2 : " << is_equal(c1, c2) << endl;
    cout << "c1 != c2 : " << is_not_equal(c1, c2) << endl;
    c4 = add(c2, c3);
    cout << "c4 = c2 + c3, c4 = "; output(c4); cout << endl;
}
void test_std_complex() {
    using std::cout;
    using std::endl;
    using std::boolalpha;
    cout << "std::complex<double>对象测试: " << endl;
    std::complex<double> c1;
    std::complex<double> c2(3, -4);
    std::complex<double> c3(c2);
    std::complex<double> c4 = c2;
    std::complex<double> c5 = 3.5;
    const std::complex<double> c6(3.5);
    cout << "c1 = " << c1 << endl;
    cout << "c2 = " << c2 << endl;
    cout << "c3 = " << c3 << endl;
    cout << "c4 = " << c4 << endl;
    cout << "c5 = " << c5 << endl;
    cout << "c6.real = " << c6.real()
         << ", c6.imag = " << c6.imag() << endl << endl;
    cout << "复数运算测试: " << endl;
    cout << "abs(c2) = " << abs(c2) << endl;
    c1 += c2;
    cout << "c1 += c2, c1 = " << c1 << endl;
    cout << boolalpha;
    cout << "c1 == c2 : " << (c1 == c2)<< endl;
    cout << "c1 != c2 : " << (c1 != c2) << endl;
    c4 = c2 + c3;
    cout << "c4 = c2 + c3, c4 = " << c4 << endl;
}
int main() {
    std::cout << "*******测试1: 自定义类Complex*******\n";
    test_Complex();
    std::cout << "\n*******测试2: 标准库类模板complex*******\n";
    test_std_complex();
}

问题与讨论

问题1
1.必须加const关键字,报错信息:passing 'const Complex' as 'this' argument discards qualifiers
2.不能编译。add()会修改成员变量,const对象只能调用const成员函数,禁止修改对象。体现封装。
问题2
标准库更简洁。C++ 中的运算符就是函数的一种缩写,因为它内部进行了重载,给这些运算符赋予了类似于函数的功能。
问题三
1.不是必须的,可以通过public的real(),imag()读取接口来实现。
2.不是友元,https://en.cppreference.com/w/cpp/numeric/complex/abs
3.friend在需要高效访问私有成员,并且没办法添加公共接口的时候使用。

任务三

源代码

点击查看代码
PlayerControl.h
```plaintext
#pragma once
#include <string>

enum class ControlType {Play, Pause, Next, Prev, Stop, Unknown};

class PlayerControl {
public:
    PlayerControl();

    ControlType parse(const std::string& control_str);  
    void execute(ControlType cmd) const;               
    static int get_cnt();

private:
    static int total_cnt;
};
PlayerControl.cpp
#include "PlayerControl.h"

#include <algorithm>
#include <iostream>
#include <cctype>

int PlayerControl::total_cnt = 0;

PlayerControl::PlayerControl() {}

ControlType PlayerControl::parse(const std::string& control_str) {
    std::string lower = control_str;
    std::transform(lower.begin(), lower.end(), lower.begin(),
                   [](unsigned char c) { return std::tolower(c); });

    if (lower == "play")  return ControlType::Play;
    if (lower == "pause") return ControlType::Pause;
    if (lower == "next")  return ControlType::Next;
    if (lower == "prev")  return ControlType::Prev;
    if (lower == "stop")  return ControlType::Stop;

    return ControlType::Unknown;
}

void PlayerControl::execute(ControlType cmd) const {
    ++total_cnt;

    switch (cmd) {
    case ControlType::Play:  std::cout << "[play] Playing music...\n";        break;
    case ControlType::Pause: std::cout << "[Pause] Music paused\n";          break;
    case ControlType::Next:  std::cout << "[Next] Skipping to next track\n"; break;
    case ControlType::Prev:  std::cout << "[Prev] Back to previous track\n"; break;
    case ControlType::Stop:  std::cout << "[Stop] Music stopped\n";          break;
    default:                 std::cout << "[Error] unknown control\n";       break;
    }
}

int PlayerControl::get_cnt() {
    return total_cnt;
}
task3.cpp
```plaintext

include

include "PlayerControl.h"

void test() {
PlayerControl controller;
std::string control_str;
std::cout << "Enter Control: (play/pause/next/prev/stop/quit):\n";

while (std::cin >> control_str) {
if (control_str == "quit")
break;

ControlType cmd = controller.parse(control_str);
controller.execute(cmd);
std::cout << "Current Player control: " << PlayerControl::get_cnt() << "\n\n";
}
}

int main() {
test();
return 0;
}

运行结果截图

image

问题与讨论

问题:因为total_cnt是static静态成员,它属于整个类,不属于某一个对象。const成员函数里的const,只是限制不能修改当前这个对象自己的成员变量**;而静态成员是所有对象共享的,存在类里面、不在对象里面,所以不受这个 const 限制。因此在 const 函数里照样可以++total_cnt。如果total_cnt不是普通成员,那在const函数里修改它就会报错。

任务四

源代码

点击查看代码
Fraction.h
```plaintext
#pragma once
#include <string>

class Fraction {
public:
    static const std::string doc;

    Fraction(int up0, int down0 = 1);
    Fraction(const Fraction& other) = default;

    int get_up() const;
    int get_down() const;

    Fraction negative() const;

private:
    int up;
    int down;

    void simplify();
};

namespace frac {
    void output(const Fraction& f);
    Fraction add(const Fraction& a, const Fraction& b);
    Fraction sub(const Fraction& a, const Fraction& b);
    Fraction mul(const Fraction& a, const Fraction& b);
    Fraction div(const Fraction& a, const Fraction& b);
}
Fraction.cpp
```plaintext
#include "Fraction.h"

#include <iostream>
#include <stdexcept>
#include <cstdlib>

int get_gcd(int a, int b)
{
    a = abs(a);
    b = abs(b);
    while (b != 0)
    {
        int r = a % b;
        a = b;
        b = r;
    }
    return a;
}

const std::string Fraction::doc =
    "Fraction类 v 0.01版.\n"
    "目前仅支持分数对象的构造、输出、加/减/乘/除运算.";

Fraction::Fraction(int up0, int down0) : up{up0}, down{down0} {
    if (down == 0)
        throw std::invalid_argument("Fraction: 分母不能为0");
    simplify();
}

int Fraction::get_up() const { return up; }

int Fraction::get_down() const { return down; }

Fraction Fraction::negative() const {
    return Fraction(-up, down);
}

void Fraction::simplify() {
    if (down < 0) {
        up = -up;
        down = -down;
    }

    int g = get_gcd(up, down);
    if (g != 0) {
        up /= g;
        down /= g;
    }
}

namespace frac {

void output(const Fraction& f) {
    if (f.get_down() == 1) {
        std::cout << f.get_up();
    } else {
        std::cout << f.get_up() << "/" << f.get_down();
    }
}

Fraction add(const Fraction& a, const Fraction& b) {
    int up = a.get_up() * b.get_down() + b.get_up() * a.get_down();
    int down = a.get_down() * b.get_down();
    return Fraction(up, down);
}

Fraction sub(const Fraction& a, const Fraction& b) {
    int up = a.get_up() * b.get_down() - b.get_up() * a.get_down();
    int down = a.get_down() * b.get_down();
    return Fraction(up, down);
}

Fraction mul(const Fraction& a, const Fraction& b) {
    return Fraction(a.get_up() * b.get_up(), a.get_down() * b.get_down());
}

Fraction div(const Fraction& a, const Fraction& b) {
    return Fraction(a.get_up() * b.get_down(), a.get_down() * b.get_up());
}

}  

task4.cpp

#include <iostream>
#include "Fraction.h"

void test1() {
    using std::cout;
    using std::endl;

    cout << "Fraction类测试: " << endl;
    cout << Fraction::doc << endl << endl;

    Fraction f1(5);
    Fraction f2(3, -4), f3(-18, 12);
    Fraction f4(f3);
    cout << "f1 = "; frac::output(f1); cout << endl;
    cout << "f2 = "; frac::output(f2); cout << endl;
    cout << "f3 = "; frac::output(f3); cout << endl;
    cout << "f4 = "; frac::output(f4); cout << endl;

    const Fraction f5(f4.negative());
    cout << "f5 = "; frac::output(f5); cout << endl;
    cout << "f5.get_up() = " << f5.get_up()
         << ", f5.get_down() = " << f5.get_down() << endl;

    cout << "f1 + f2 = "; frac::output(frac::add(f1, f2)); cout << endl;
    cout << "f1 - f2 = "; frac::output(frac::sub(f1, f2)); cout << endl;
    cout << "f1 * f2 = "; frac::output(frac::mul(f1, f2)); cout << endl;
    cout << "f1 / f2 = "; frac::output(frac::div(f1, f2)); cout << endl;
    cout << "f4 + f5 = "; frac::output(frac::add(f4, f5)); cout << endl;
}

void test2() {
    using std::cout;
    using std::endl;

    Fraction f6(42, 55), f7(0, 3);
    cout << "f6 = "; frac::output(f6); cout << endl;
    cout << "f7 = "; frac::output(f7); cout << endl;
    cout << "f6 / f7 = "; frac::output(frac::div(f6, f7)); cout << endl;
}

int main() {
    test1();
    test2();
    return 0;
}

运行结果截图

image

问题与讨论

问题:选择方案二,这些加减乘除、输出函数,用get_up ()和get_down ()就能拿到分子分母来计算,不用直接访问私有变量,所以不用写成友元。放到frac命名空间里,不容易和别的函数名字冲突。这种写法不会破坏类的封装,更安全。

posted @ 2026-11-19 15:43  lp99  阅读(5)  评论(0)    收藏  举报