任务一

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


  • 运行测试截图
    image

  • 问题一
    普通构造函数 T(int x = 0, int y = 0);
    功能:根据传入的参数(或默认值)创建并初始化一个新对象。
    调用时机:直接声明定义新对象时。

    复制构造函数 T(const T &t);
    功能:用已存在的对象“克隆”出一个新对象(把原对象的数据照抄过来)。
    调用时机:用一个普通对象去初始化另一个新对象时。

    移动构造函数 T(T &&t);
    功能:把即将销毁的临时对象里的数据直接挪给新对象,避免复制,提高效率。
    调用时机:用临时对象,或者被 std::move() 转换后的对象去初始化新对象时。

    析构函数 ~T();
    功能:在对象生命周期结束时进行清理工作。
    调用时机:对象所在作用域结束、对象被delete、程序结束时。
    T t1:触发了普通构造函数。
    T t2(3, 4):触发了普通构造函数。
    T t3(t2):t2 是一个已有对象,触发了复制构造函数。
    T t4(std::move(t2)):std::move 把t2变成了临时对象(右值),触发了移动构造函数。

  • 问题二

  • 报错信息
    image

  • 原因
    t.h被t.cpp和task1.cpp两个源文件包含(#include "t.h")。C++在编译时,各个源文件(.cpp)会分别生成目标文件(.o/.obj)。如果静态成员变量(非inline变量的情况下)在头文件中进行初始化,那么包含该头文件的所有源文件都会生成一份同名变量的实体。到了链接阶段,链接器会发现有多个相同名字的符号,违反了单一定义规则,因此导致链接失败。

  • 问题三
    t1到t4定义在test()函数内的一对花括号{}中,属于局部变量。它们的作用域和生命周期从定义它们的那一行开始,到包含它们的花括号}结束。当程序运行到}时,它们会按照构造的逆序(析构顺序:t4, t3, t2, t1)被自动销毁。
    不能通过t1访问私有成员m1、m2,这体现了类的封装性。

  • 问题四
    throw功能:用于抛出异常。当程序执行到throw语句时,会立刻中断当前正常的执行流程,将异常对象传递给调用栈上层,寻找能够捕获(catch)该异常的代码块。如果没有被捕获,程序会调用std::terminate导致崩溃(Abort)。
    image
    改成2后程序崩溃了。当抛出异常时,函数栈开始展开。C++保证在退出作用域时,会调用已经成功构造的局部对象的析构函数,因此已经创建的t1和t2会被正常销毁。

任务二

  • Complex.h源码
点击查看代码
#pragma once
#include <string>

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

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

    static const std::string doc; 

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

private:
    double m_real;
    double m_imag;
};
  • Complex.cpp源码
点击查看代码
#include "Complex.h"
#include <iostream>
#include <cmath>

const std::string Complex::doc{"Complex类: 实现复数基本运算"};

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) {
    std::cout << "(" << c.m_real << ", " << c.m_imag << ")";
}

double abs(const Complex &c) {
    return std::sqrt(c.m_real * c.m_real + c.m_imag * c.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);
}

Complex add(const Complex &c1, const Complex &c2) {
    return Complex(c1.m_real + c2.m_real, c1.m_imag + c2.m_imag);
}
  • 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();
}
  • 运行测试截图
    屏幕截图 2026-11-19 161733

  • 问题一
    ①必须在成员函数声明的参数列表后面加上const关键字。
    如果不加,例如我把double real() const;后面的const删去,就会出现如下图所示的报错信息:
    image
    ②不能编译通过。
    因为c6是常对象,只能调用带有const修饰的成员函数。而add()函数没有const修饰,所以编译器会阻止对常对象调用可能修改其内容的函数。
    体现了类的常量正确性保护机制。将数据设为const后,编译器会在编译阶段强制检查,防止意外修改,保障了数据的安全性。

  • 问题二
    标准库类模板std::complex更简洁。例如c1+=c2比c1.add(c2)更接近数学表达式,c4=c2+c3比c4=add(c2, c3)更直观,cout<<c1比output(c1)更符合C++习惯。
    内在关联:C++中的运算符本质上是函数的另一种表现形式。标准库之所以用法简洁,是因为它通过运算符重载,把冗长的函数调用封装成了符合人类直觉的数学符号。

  • 问题三
    不是必须的。
    能实现。
    思路:如果不用friend,只要Complex类提供了足够的public接口,普通非成员函数就可以通过调用这些接口来完成任务。

任务三

  • 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 <iostream>
#include <cctype>     // 补充头文件,用于 tolower

int PlayerControl::total_cnt = 0;

PlayerControl::PlayerControl() {}

// 补足实现
ControlType PlayerControl::parse(const std::string& control_str) {
    // 1. 将输入字符串统一转为小写,实现大小写不敏感
    std::string lower_str = control_str;
    std::transform(lower_str.begin(), lower_str.end(), lower_str.begin(),
                   [](unsigned char c) { return std::tolower(c); });

    // 2. 匹配并返回对应枚举
    if (lower_str == "play")  return ControlType::Play;
    if (lower_str == "pause") return ControlType::Pause;
    if (lower_str == "next")  return ControlType::Next;
    if (lower_str == "prev")  return ControlType::Prev;
    if (lower_str == "stop")  return ControlType::Stop;

    // 未匹配返回 Unknown
    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();
}
  • 运行测试截图
    image

  • 问题回答
    因为total_cnt被声明为static静态成员变量。
    const成员函数不会修改当前对象的非静态成员变量。但是,静态成员变量total_cnt属于整个类,而不是属于某一个具体的对象实例。它存储在全局静态区,不存在于对象的内存布局中。在const成员函数内部修改静态成员变量,并没有违背const保护当前对象状态的原则,因此编译器是允许的。

任务四

  • Fraction.h源码
点击查看代码
#pragma once

#include <string>
#include <iostream>

class Fraction {
public:
    // 构造函数,带默认参数,支持隐式转换
    Fraction(int up = 0, int down = 1);
    
    // 复制构造函数(编译器会自动生成,这里为了明确写出)
    Fraction(const Fraction& other) = default;

    // 获取分子和分母
    int get_up() const;
    int get_down() const;

    // 求负运算:返回一个新的分数对象,原对象不变
    Fraction negative() const;

    // 静态常量:类说明
    static const std::string doc;

    // 声明友元函数
    friend void output(const Fraction& f);
    friend Fraction add(const Fraction& f1, const Fraction& f2);
    friend Fraction sub(const Fraction& f1, const Fraction& f2);
    friend Fraction mul(const Fraction& f1, const Fraction& f2);
    friend Fraction div(const Fraction& f1, const Fraction& f2);

private:
    int up;   // 分子
    int down; // 分母

    // 辅助工具函数:化简分数
    void simplify();
};
  • Fraction.cpp源码
点击查看代码
#include "Fraction.h"
#include <stdexcept>
#include <cmath>

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

// 辅助函数:求最大公约数
static int gcd(int a, int b) {
    a = std::abs(a);
    b = std::abs(b);
    while (b != 0) {
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}

// 构造函数
Fraction::Fraction(int u, int d) : up(u), down(d) {
    if (down == 0) {
        throw std::invalid_argument("Fraction: 分母不能为0");
    }
    simplify(); // 创建时直接化简
}

// 化简分数
void Fraction::simplify() {
    if (up == 0) {
        down = 1;
        return;
    }
    // 统一符号:将负号放在分子上
    if (down < 0) {
        up = -up;
        down = -down;
    }
    int divisor = gcd(up, down);
    up /= divisor;
    down /= divisor;
}

// 成员函数
int Fraction::get_up() const { return up; }
int Fraction::get_down() const { return down; }

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

// 友元函数实现
void output(const Fraction& f) {
    if (f.down == 1) {
        std::cout << f.up;
    } else {
        std::cout << f.up << "/" << f.down;
    }
}

Fraction add(const Fraction& f1, const Fraction& f2) {
    return Fraction(f1.up * f2.down + f2.up * f1.down, f1.down * f2.down);
}

Fraction sub(const Fraction& f1, const Fraction& f2) {
    return Fraction(f1.up * f2.down - f2.up * f1.down, f1.down * f2.down);
}

Fraction mul(const Fraction& f1, const Fraction& f2) {
    return Fraction(f1.up * f2.up, f1.down * f2.down);
}

Fraction div(const Fraction& f1, const Fraction& f2) {
    // 注意:f2.up 如果为0,那么新分母 f1.down * f2.up 将为0
    // 构造新对象时会触发分母为0的异常
    return Fraction(f1.up * f2.down, f1.down * f2.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 = "; output(f1); cout << endl;
    cout << "f2 = "; output(f2); cout << endl;
    cout << "f3 = "; output(f3); cout << endl;
    cout << "f4 = "; output(f4); cout << endl;

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

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

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

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

int main() {
    std::cout << "测试1: Fraction类基础功能测试\n";
    test1();

    std::cout << "\n测试2: 分母为0测试: \n";
    test2();
}
  • 运行测试截图
    image

  • 问题回答
    方案1:分数类 + 友元函数。
    决策理由:

  1. 代码简洁、直观:如果使用普通非成员函数,为了保持类的封装性,必须通过get_up()和get_down()接口来获取私有数据,这会导致函数体内充斥着大量的函数调用。而使用友元函数,可以直接访问类的私有数据成员,大大简化了代码。
  2. 性能优势:友元函数直接访问成员变量,减少了成员函数调用的开销。
  3. 符合直觉:像add、sub这种双目运算,本质上是对两个对象进行同等地位的操作,将其声明为类的友元,在语法上比让其中一个对象作为发起者(如f1.add(f2))更加符合数学逻辑。