面向对象程序设计 实验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();          // 显示当前T类对象总数

    friend void output(const T &t); // 友元, 以(m1, m2)形式输出对象t

    static const std::string doc;       // 类T的描述信息
    static const int MAX_CNT;           // 类T对象上限

private:
    int m1, m2;  // 对象数据成员

    static int current_cnt;    // 当前T类对象数目
};

t.cpp

#include "t.h"

#include <iostream>
#include <stdexcept>
#include <string>

// static成员数据: 类内声明、类外初始化
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();
}

测试截图

Task 1 正常运行结果

问题

问题一:

T(int x = 0, int y = 0):普通构造函数。
T(const T &t):复制构造函数。用一个已有的同类对象初始化新对象时调用。
T(T &&t):移动构造函数。用右值初始化新对象时调用,可以接管原对象的资源。
~T():析构函数。对象生命期结束时做清理工作。

t1触发了普通构造函数,初始化对象,不带参数,用默认值(0, 0)
t2触发了普通构造函数,初始化对象,并且附带参数(3, 4)
t3触发了复制构造函数,直接把t2的对象复制过去
t4触发了移动构造函数,std::move(t2)把t2转成右值,t4直接接管了t2的资源

问题二:

不能。

Task 1 静态成员重复定义报错

原因:重复定义了。

问题三:

t1~t4 定义在 test() 里那对花括号 {} 中,从定义处开始到右花括号 } 结束。

生命期:执行到定义语句时创建,执行到 } 时结束,按 t4、t3、t2、t1 的顺序(和构造顺序相反)调用析构函数。

不能通过 t1 访问 m1、m2,它们是 private 成员。这体现了类的封装性。

问题四:

throw 用于抛出异常。抛出后当前函数立即停止执行,程序沿调用链往上找匹配的 catch;如果一直找不到,就调用 std::terminate() 终止程序。(由AI生成)

崩溃了
Task 1 MAX_CNT 改为 2 的运行结果

已经创建的 t1、t2 不会被正常销毁。AI说因为异常没有被 catch 时,标准规定是否进行栈展开由实现决定,g++/clang 都是直接调用 terminate 结束程序,不会再去调用局部对象的析构函数。如果在 main 里加上 try-catch,栈展开时 t1、t2 就会被正常析构,但我看了别的同学的博客,有人的AI说会被销毁

我让AI查阅资料找到了标准草案,C++ 标准规定:找不到匹配的 catch 时,程序会调用 std::terminate(),调用前是否展开栈由实现决定。https://eel.is/c++draft/except.terminate#2 而那位同学漏掉了一个前提:异常被外层 catch 捕获,且转入 catch 的过程退出了这些对象所在的作用域。我在 main() 中用 try-catch 包住 test() 再运行,确实看到了两次 T destructor called.

实验任务二

源码以及运行测试截图

Complex.h

#pragma once

#include <string>

class Complex {
public:
    Complex(double r = 0, double i = 0);

    double real() const;
    double imag() const;
    void add(const Complex &c);

    friend void output(const Complex &c);
    friend double abs(const Complex &c);
    friend Complex add(const Complex &c1, const Complex &c2);
    friend bool is_equal(const Complex &c1, const Complex &c2);
    friend bool is_not_equal(const Complex &c1, const Complex &c2);

    static const std::string doc;

private:
    double m_real, m_imag;
};

Complex.cpp

#include "Complex.h"

#include <cmath>
#include <iostream>

const std::string Complex::doc{"a simplified complex class"};

Complex::Complex(double r, double i): m_real{r}, m_imag{i} {}

double Complex::real() const {
    return m_real;
}

double Complex::imag() const {
    return m_imag;
}

void Complex::add(const Complex &c) {
    m_real += c.m_real;
    m_imag += c.m_imag;
}

void output(const Complex &c) {
    if (c.m_imag >= 0)
        std::cout << c.m_real << " + " << c.m_imag << "i";
    else
        std::cout << c.m_real << " - " << -c.m_imag << "i";
}

double abs(const Complex &c) {
    return std::sqrt(c.m_real * c.m_real + c.m_imag * c.m_imag);
}

Complex add(const Complex &c1, const Complex &c2) {
    return Complex(c1.m_real + c2.m_real, c1.m_imag + c2.m_imag);
}

bool is_equal(const Complex &c1, const Complex &c2) {
    return c1.m_real == c2.m_real && c1.m_imag == c2.m_imag;
}

bool is_not_equal(const Complex &c1, const Complex &c2) {
    return !is_equal(c1, c2);
}

task2.cpp

#include <iomanip>
#include <iostream>
#include <complex>

#include "Complex.h"

// 测试自定义类Complex
void test_Complex() {
    using std::cout;
    using std::endl;
    using std::boolalpha;

    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;
}

// 测试标准库类模板complex
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();
}

测试截图

Task 2 复数类运行结果

问题

问题一:

① 必须加 const,写成 double real() const;。如果不加,const 对象 c6 调用它们时编译报错:

Task 2 去掉 const 后的编译报错

② 不能编译通过(题目里"允许"应为"不允许")。add() 会修改实部和虚部,不是 const 成员函数,const 对象只能调用 const 成员函数。

Task 2 常对象调用 add 的编译报错

这体现了类的 const 保护机制:常对象 + 常成员函数。

问题二:

std::complex 更简洁,用 +、+=、==、<< 写出来就跟数学式子一样,一眼就能看懂。
是因为它内部进行了重载,给这些运算符赋予了类似于函数的功能。

问题三:

① 不是必须的。Complex 已经提供了公有的 real()、imag(),普通非成员函数通过这两个接口就能拿到数据,比如:

double abs(const Complex &c) {
    return std::sqrt(c.real() * c.real() + c.imag() * c.imag());
}

Complex add(const Complex &c1, const Complex &c2) {
    return Complex(c1.real() + c2.real(), c1.imag() + c2.imag());
}

output、is_equal 等同理。这样功能完全一样,而且不用开放私有成员,封装更好。

② 没有。链接:https://en.cppreference.com/w/cpp/numeric/complex/abs

③ friend 会让外部函数直接访问私有成员,破坏封装、增加耦合,所以工业代码里能不用就不用。只有在函数确实需要访问内部数据、公有接口又不够或者效率太低时才考虑。

实验任务三

源码以及运行测试截图

PlayerControl.h

#pragma once

#include <string>

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

class PlayerControl {
public:
    PlayerControl();

    ControlType parse(const std::string& control_str);   // 实现std::string --> ControlType转换
    void execute(ControlType cmd) const;   // 执行控制操作(以打印输出模拟)       

    static int get_cnt();

private:
    static int total_cnt;   
};

PlayerControl.cpp

#include "PlayerControl.h"

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

int PlayerControl::total_cnt = 0;

PlayerControl::PlayerControl() {}

// 1. 将输入字符串统一成转为小写,实现大小写不敏感
// 2. 匹配"play"/"pause"/"next"/"prev"/"stop"并返回对应枚举;
//    未匹配的字符串返回ControlType::Unknown
ControlType PlayerControl::parse(const std::string& control_str) {
    std::string str = control_str;
    std::transform(str.begin(), str.end(), str.begin(),
                   [](unsigned char c) { return std::tolower(c); });

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

    return ControlType::Unknown;
}

void PlayerControl::execute(ControlType cmd) const {
    // 每执行一次控制操作(含未知命令),total_cnt自增 1
    ++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

#include <iostream>

#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();
}

测试截图

Task 3 播放器控制运行结果

问题

问题一:

total_cnt 是 static 成员,不属于某个具体对象。const 成员函数的 const 只修饰 this 指针,保证不改动当前对象的非静态数据成员。total_cnt 访问静态成员时不经过 this,所以不受 const 限制。

思考(选做):

只需要改 PlayerControl.cpp 中 execute() 的输出字符串,把 [play] 这类文字前缀换成 emoji,PlayerControl.h 和 task3.cpp 不用动。源文件要保存为 UTF-8 编码;

PlayerControl.h

#pragma once

#include <string>

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

class PlayerControl {
public:
    PlayerControl();

    ControlType parse(const std::string& control_str);   // 实现std::string --> ControlType转换
    void execute(ControlType cmd) const;   // 执行控制操作(以打印输出模拟)       

    static int get_cnt();

private:
    static int total_cnt;   
};

PlayerControl.cpp

#include "PlayerControl.h"

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

int PlayerControl::total_cnt = 0;

PlayerControl::PlayerControl() {}

// 1. 将输入字符串统一成转为小写,实现大小写不敏感
// 2. 匹配"play"/"pause"/"next"/"prev"/"stop"并返回对应枚举;
//    未匹配的字符串返回ControlType::Unknown
ControlType PlayerControl::parse(const std::string& control_str) {
    std::string str = control_str;
    std::transform(str.begin(), str.end(), str.begin(),
                   [](unsigned char c) { return std::tolower(c); });

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

    return ControlType::Unknown;
}

void PlayerControl::execute(ControlType cmd) const {
    // 每执行一次控制操作(含未知命令),total_cnt自增 1
    ++total_cnt; 

    switch (cmd) {
    case ControlType::Play:  std::cout << "🎵 Playing music...\n"; break;
    case ControlType::Pause: std::cout << "⏸️ Music paused\n";    break;
    case ControlType::Next:  std::cout << "⏭️ Skipping to next track\n"; break;
    case ControlType::Prev:  std::cout << "⏮️ Back to previous track\n"; break;
    case ControlType::Stop:  std::cout << "⏹️ Music stopped\n"; break;
    default:                 std::cout << "❌ Unknown control\n"; break;
    }
}

int PlayerControl::get_cnt() {
    return total_cnt;
}

task3.cpp

#include <iostream>

#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();
}

测试截图

Task 3 emoji 版运行结果

实验任务四

源码以及运行测试截图

Fraction.h

#pragma once

#include <string>

class Fraction {
public:
    Fraction(int up0, int down0 = 1);

    int get_up() const;
    int get_down() const;
    Fraction negative() const;

    static const std::string doc;

private:
    void simplify();

    int up, down;
};

namespace frac {
    void output(const Fraction &f);
    Fraction add(const Fraction &f1, const Fraction &f2);
    Fraction sub(const Fraction &f1, const Fraction &f2);
    Fraction mul(const Fraction &f1, const Fraction &f2);
    Fraction div(const Fraction &f1, const Fraction &f2);
}

Fraction.cpp

#include "Fraction.h"

#include <iostream>
#include <stdexcept>

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

static int gcd(int a, int b) {
    if (a < 0) a = -a;
    if (b < 0) b = -b;
    while (b != 0) {
        int t = a % b;
        a = b;
        b = t;
    }
    return a;
}

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 (up == 0) {
        down = 1;
        return;
    }

    int g = gcd(up, down);
    up /= g;
    down /= g;

    if (down < 0) {
        up = -up;
        down = -down;
    }
}

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 &f1, const Fraction &f2) {
    return Fraction(f1.get_up() * f2.get_down() + f2.get_up() * f1.get_down(),
                    f1.get_down() * f2.get_down());
}

Fraction sub(const Fraction &f1, const Fraction &f2) {
    return add(f1, f2.negative());
}

Fraction mul(const Fraction &f1, const Fraction &f2) {
    return Fraction(f1.get_up() * f2.get_up(), f1.get_down() * f2.get_down());
}

Fraction div(const Fraction &f1, const Fraction &f2) {
    return Fraction(f1.get_up() * f2.get_down(), f1.get_down() * f2.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() {
    std::cout << "测试1: Fraction类基础功能测试\n";
    test1();

    std::cout << "\n测试2: 分母为0测试: \n";
    test2();
}

测试截图

Task 4 分数运算和除零测试

问题

问题一:

选的是方案2:分数类 + 命名空间自由函数(命名空间 frac),测试代码里的调用都加了 frac:: 前缀。

理由:

  1. 类已经提供了 get_up()、get_down() 两个公有接口,output 和加减乘除只用这两个接口就能实现,不需要访问私有成员,没必要用友元去破坏封装。
  2. 构造函数里统一做了约分和符号处理,运算函数只管按公式算出分子分母,再交给构造函数生成新对象就行。
  3. 放进命名空间可以避免和其他同名函数冲突。