实验2

实验2

1. 实验任务1

1.1 源代码如下

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

1.3 问题回答

问题1:
T(int x = 0, int y = 0) 是普通构造函数,也可以当作默认构造函数使用。它的功能是用 x、y初始化m1m2,检查对象数是否达到上限,然后把current_cnt加1。调用时机是创建对象时给出0~2个int实参。t1使用默认实参构造t2用(3, 4)构造,二者都调用这个普通构造函数。
T(const T &t)是复制构造函数。复制 m1、m2 并增加对象计数。调用时机包括:用同类型对象直接初始化新对象、对象按值传参、对象按值返回且复制没有被省略时。t3(t2) 用 t2 初始化 t3,调用复制构造函数。
T(T &&t) 是移动构造函数。它的功能是用一个右值(将亡值)初始化新对象,接管原对象的资源并增加对象计数。调用时机包括:用 std::move(...)的结果初始化对象,或者用临时对象初始化对象。t4(std::move(t2))调用移动构造函数。
~T()是析构函数。它的功能是在对象生命期结束时释放对象占用的资源,并把current_cnt减 1。调用时机是对象离开作用域、被 delete,或者临时对象销毁时。
问题2:
不能正确完成构建。各个 .cpp 文件单独编译时一般不会报错,但链接会失败。
原因是t.h同时被t.cpp和task1.cpp包含,三个静态成员的定义会分别出现在两个翻译单元中:
编译报错截图:
image
问题3:
t1~t4 都声明在test()内部。它们的作用域(名字可见的范围)从各自的声明点开始,到花括号结束;生命期(对象真正存在的时间)从构造函数执行完成开始,到离开该花括号时结束。离开花括号时,四个对象按构造的逆序析构,即 t4、t3、t2、t1。
在 test()中不能通过 t1访问 m1、m2。写成 t1.m1 或 t1.m2 会编译报错,提示 m1、m2 是 T 的私有成员。访问权限是按类划分的,不是按函数或代码块划分的:即使 test() 能看到t1这个对象,也不能看到它的私有成员。这体现了类的封装和信息隐藏特性,私有成员只能由类的成员函数(以及声明为友元的函数)访问,类外只能使用公有接口。
问题4:
throw用来抛出异常。执行throw std::runtime_error(...)时,当前函数立即停止正常执行,异常对象沿调用栈向上传播,寻找匹配的catch。如果一直没有被捕获,程序会调用std::terminate,导致异常终止。
把 T::MAX_CNT改成 2 后,t1、t2可以正常构造,此时 current_cnt已经等于 2。构造t3时,复制构造函数在自增计数之前检查到 current_cnt == MAX_CNT,于是抛出 std::runtime_error。程序不是正常结束,而是崩溃/异常终止,输出中会出现:

terminate called after throwing an instance of 'std::runtime_error'
  what():  T: maximum object count exceeded

在 Windows/MSVC 环境下,还可能看到 abort() has been called 一类的提示。
已经构造完成的对象会被正常销毁。异常从 t3 的构造函数抛出后,栈展开(stack unwinding)会销毁当前作用域内已经完整构造的对象,因此 t2、t1 会依次调用析构函数,输出两条 T destructor called.,current_cnt 回到 0。正在构造的 t3不会被析构,因为它的构造函数没有执行完,对象的生命期还没有正式开始,C++ 不会对“构造未完成”的对象调用析构函数。
运行截图:image

2. 实验任务2

2.1 源代码如下

Complex.h

#pragma once
#include <string>
class Complex {
public:
    Complex(double real_part = 0.0, double imag_part = 0.0);  
    Complex(const Complex &other);                            
    double real() const;   
    double imag() const;   
    void add(const Complex &other);  
    static const std::string doc;    
    friend void output(const Complex &c);                              
    friend double abs(const Complex &c);                               
    friend Complex add(const Complex &lhs, const Complex &rhs);    
    friend bool is_equal(const Complex &lhs, const Complex &rhs);   
    friend bool is_not_equal(const Complex &lhs, const Complex &rhs);  
private:
    double m_real;  
    double m_imag;  
};

Complex.cpp

#include "Complex.h"
#include <cmath>
#include <iostream>
const std::string Complex::doc{"a simplified complex class"};
Complex::Complex(double real_part, double imag_part)
    : m_real{real_part}, m_imag{imag_part} {}
Complex::Complex(const Complex &other)
    : m_real{other.m_real}, m_imag{other.m_imag} {}
double Complex::real() const {
    return m_real;
}
double Complex::imag() const {
    return m_imag;
}
void Complex::add(const Complex &other) {
    m_real += other.m_real;
    m_imag += other.m_imag;
}
// 友元:按 a+bi 形式输出;虚部为负时输出 a - bi
void output(const Complex &c) {
    std::cout << c.m_real;
    if (c.m_imag < 0.0) {
        std::cout << " - " << -c.m_imag << "i";
    } else {
        std::cout << " + " << c.m_imag << "i";
    }
}
// 友元:复数取模
double abs(const Complex &c) {
    return std::hypot(c.m_real, c.m_imag);
}
// 友元:两个复数相加,返回新对象
Complex add(const Complex &lhs, const Complex &rhs) {
    return Complex(lhs.m_real + rhs.m_real, lhs.m_imag + rhs.m_imag);
}
// 友元:判断两个复数是否相等
bool is_equal(const Complex &lhs, const Complex &rhs) {
    return lhs.m_real == rhs.m_real && lhs.m_imag == rhs.m_imag;
}
// 友元:判断两个复数是否不相等
bool is_not_equal(const Complex &lhs, const Complex &rhs) {
    return !is_equal(lhs, rhs);
}

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

运行截图:image

2.3 问题回答

问题1①:
必须在成员函数的参数列表后面加 const,即声明为:
加 const表示这个成员函数不会修改对象的非静态数据成员,因此可以被const对象调用。如果不加c6是const Complex对象,编译器不能把 const Complex类型的this指针转换成 Complex,会报错“将‘const Complex’作为‘this’参数传递给‘double Complex::real()’会丢弃限定符”(discards qualifiers)。
问题1②:
不能编译通过。c6是const Complex对象,初始化后是只读的;而add()只能声明为非const成员函数。
这体现了const保护机制
问题2:
标准库std::complex的用法更简洁。
两者存在内在关联:运算符本质上就是函数,它只是给函数调用换了一种更自然、更简洁的写法。
问题3①:
不是必须的。只要类的公有接口足够表达这些操作,就不需要友元。友元的作用是省去访问器调用,允许非成员函数直接读写私有成员。
问题3②:
不是。std::abs(std::complex)是定义在中、位于std命名空间里的非成员函数模板,它通过complex的公有 real()、imag()成员取得实部和虚部来计算模,并不是 complex类的友元。参考页面:std::abs(std::complex) - cppreference。
问题3③:
只有当非成员函数或运算符必须直接读写私有表示,且为此增加公有接口会泄露实现或明显低效时才用 friend,例如 operator<<、operator==、紧密协作的迭代器或工厂。能用公有接口完成就不用友元;友元会加重耦合,应少而精。

3. 实验任务3

3.1 源代码如下

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);  // 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() {}
ControlType PlayerControl::parse(const std::string &control_str) {
    std::string lower = control_str;
    std::transform(lower.begin(), lower.end(), lower.begin(),
                   [](unsigned char ch) {
                       return static_cast<char>(std::tolower(ch));
                   });
    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

#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.png(uploading...)}
image

3.3 问题回答

const成员函数承诺的是不修改当前对象的非静态数据成员,也就是不通过this修改对象状态。total_cnt是static成员,它属于整个PlayerControl类,被所有对象共享,并不存放在某个具体对象内部。const限定作用于对象的非静态成员,不作用于静态成员,所以在const成员函数中修改 total_cnt是合法的。

4. 实验任务4

4.1 源代码如下

Fraction.h

#pragma once
#include <string>
class Fraction {
public:
    explicit Fraction(int up = 0, int down = 1);  // 默认/普通构造函数
    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 &lhs, const Fraction &rhs);       // 加法
    friend Fraction sub(const Fraction &lhs, const Fraction &rhs);       // 减法
    friend Fraction mul(const Fraction &lhs, const Fraction &rhs);       // 乘法
    friend Fraction div(const Fraction &lhs, const Fraction &rhs);       // 除法
private:
    int m_up;    // 分子
    int m_down;  // 分母
    void normalize();  // 约分、统一符号,并检查分母是否为 0
};

Fraction.cpp

#include "Fraction.h"
#include <iostream>
#include <numeric>
#include <stdexcept>
const std::string Fraction::doc{
    "Fraction类 v 0.01版.\n"
    "目前仅支持分数对象的构造、输出、加/减/乘/除运算."};
Fraction::Fraction(int up, int down) : m_up{up}, m_down{down} {
    normalize();
}
// 统一符号并约分:分母始终为正,分子带符号
void Fraction::normalize() {
    if (m_down == 0) {
        throw std::invalid_argument("Fraction: 分母不能为0");
    }
    if (m_down < 0) {
        m_up = -m_up;
        m_down = -m_down;
    }
    const int g = std::gcd(m_up, m_down);
    m_up /= g;
    m_down /= g;
}
int Fraction::get_up() const {
    return m_up;
}
int Fraction::get_down() const {
    return m_down;
}
Fraction Fraction::negative() const {
    return Fraction(-m_up, m_down);
}
// 友元:输出化简后的分数
void output(const Fraction &f) {
    std::cout << f.m_up << "/" << f.m_down;
}
// 友元:加法
Fraction add(const Fraction &lhs, const Fraction &rhs) {
    return Fraction(lhs.m_up * rhs.m_down + rhs.m_up * lhs.m_down,
                    lhs.m_down * rhs.m_down);
}
// 友元:减法
Fraction sub(const Fraction &lhs, const Fraction &rhs) {
    return Fraction(lhs.m_up * rhs.m_down - rhs.m_up * lhs.m_down,
                    lhs.m_down * rhs.m_down);
}
// 友元:乘法
Fraction mul(const Fraction &lhs, const Fraction &rhs) {
    return Fraction(lhs.m_up * rhs.m_up, lhs.m_down * rhs.m_down);
}
// 友元:除法;除数为 0 时抛出异常
Fraction div(const Fraction &lhs, const Fraction &rhs) {
    if (rhs.m_up == 0) {
        throw std::invalid_argument("Fraction: 除数不能为0");
    }
    return Fraction(lhs.m_up * rhs.m_down, lhs.m_down * rhs.m_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

4.3 问题回答

选择方案1:
因为,给定的测试代码就是以output(f1)、add(f1, f2) 这种非成员函数形式调用的,采用友元函数可以直接匹配测试代码,不需要给测试代码加命名空间前缀。第二,加、减、乘、除和输出本来就是分数类型的整体接口,友元函数可以直接读写 m_up、m_down,不必为了运算再增加一组公有访问器,代码更短、可读性更好,也便于在函数内部直接调用构造函数完成约分和符号统一。

posted @ 2026-11-19 23:33  TDTTDT  阅读(1)  评论(0)    收藏  举报