实验2

屏幕截图 2026-11-18 141134

1. 实验任务1:简单类 T

本任务通过类 T 验证普通构造、复制构造、移动构造、析构、静态成员、友元以及 const 静态数据的用法。

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

一、实验任务1

问题1:各类函数的功能与调用时机

  • T(int x = 0, int y = 0):普通构造函数,可用 0、1 或 2 个参数创建对象。
  • T(const T &t):复制构造函数,用已有对象初始化新对象。
  • T(T &&t):移动构造函数,用右值对象构造新对象,可避免不必要的资源复制。
  • ~T():析构函数,在对象生命周期结束时自动调用,释放对象占用的资源。

结合测试代码:

  • T t1; 使用默认参数调用普通构造函数。
  • T t2(3, 4); 调用带两个参数的普通构造函数。
  • T t3(t2); 调用复制构造函数。
  • T t4(std::move(t2)); 把 t2 转换为右值,调用移动构造函数。

四个对象离开内部语句块时,按构造的逆序析构:t4、t3、t2、t1。

问题2:把静态成员定义移动到 t.h 末尾

不能正确构建。

#pragma once 只能防止同一个源文件多次包含头文件,不能防止不同源文件分别包含一份定义。t.cpp 和 task1.cpp 都包含 t.h 后,静态成员可能在两个目标文件中各产生一份定义,链接时通常出现类似 multiple definition 或“重复定义”的错误。

静态数据成员应在头文件中声明,在且仅在一个 .cpp 文件中定义。例如:

// t.h
static const std::string doc;

// t.cpp
const std::string T::doc{"a simple class sample"};

C++17 也可以使用 inline static 在头文件中定义静态成员,但这会改变题目给出的原始代码结构。

问题3:对象作用域、生命周期与私有成员

t1 至 t4 都在 test() 内部的花括号语句块中定义,因此:

  • 作用域是内部语句块;
  • 构造顺序是 t1、t2、t3、t4;
  • 析构顺序是 t4、t3、t2、t1;
  • 块内对象计数为 4,离开语句块后计数为 0。

不能在 test() 中直接通过 t1.m1 或 t1.m2 访问私有成员。只有 T 的成员函数以及声明为友元的 output() 可以访问它们。这体现了类的封装特性:对象通过公开接口提供服务,同时隐藏并保护内部数据。

问题4:throw 的作用及 MAX_CNT 改为 2

throw 用于抛出异常对象。代码:

throw std::runtime_error("T: maximum object count exceeded");

会创建一个 std::runtime_error 异常对象并抛出。该异常没有被 catch 捕获时,程序最终会调用 std::terminate 并异常终止。

把 MAX_CNT 改为 2 后:

  1. t1 构造成功,当前计数为 1;
  2. t2 构造成功,当前计数为 2;
  3. 构造 t3 时计数已经达到上限,复制构造函数在增加计数前抛出异常;
  4. 程序不会正常结束。

异常传播时会发生栈展开。已经完整构造的 t1 和 t2 会正常析构,通常先析构 t2,再析构 t1。正在构造的 t3 没有完整构造成功,因此不会执行 t3 的析构函数。


3861774-20261117222318825-453849087

3861774-20261117222344126-1211635395

二、实验任务2

问题1:const 对象与 const 成员函数

1. c6.real() 和 c6.imag() 应增加的限定符

应将 real() 和 imag() 声明为 const 成员函数:

double real() const;
double imag() const;

如果不加 const,const Complex c6 不能调用它们。GCC 下可能出现类似错误:

passing 'const Complex' as 'this' argument discards qualifiers

原因是普通成员函数隐含的 this 类型是 Complex*,而 const 对象只能提供 const Complex*,不能丢弃 const 限定。

2. 执行 c6.add(c2) 能否编译

不能编译。题目此处应理解为“const 对象 c6 初始化后不允许再被修改”。

add() 会修改复数的实部或虚部,不是 const 成员函数,因此不能作用于 const Complex c6。这体现了 const 对象保护机制和类的访问控制:对象一旦声明为 const,编译器就会禁止通过成员函数修改其状态。

问题2:自定义 Complex 与标准库 std::complex

自定义 Complex 标准库 std::complex<T> 对应的运算符或函数
c1.add(c2) c1 += c2 operator+=
add(c2, c3) c2 + c3 operator+
is_equal(c1, c2) c1 == c2 operator==
is_not_equal(c1, c2) c1 != c2 operator!=
output(c1) cout << c1 operator<<
abs(c2) abs(c2) 非成员函数 abs

标准库运算符形式更简洁、自然,也更接近数学表达式。

运算符本质上也是通过函数实现的。例如 c2 + c3 实际会调用 operator+(c2, c3),c1 += c2 会调用 operator+=。因此,运算符重载和普通函数之间存在直接对应关系。

问题3:辅助函数是否必须声明为友元

不是必须。如果类已经公开 real()、imag() 和构造函数,就可以使用普通非成员函数实现相同功能,例如:

double abs(const Complex &value) {
    return std::hypot(value.real(), value.imag());
}

Complex add(const Complex &left, const Complex &right) {
    return Complex(left.real() + right.real(),
                   left.imag() + right.imag());
}

声明为友元的好处是辅助函数可以直接访问私有成员,不必增加 getter,但也会增强类与外部的耦合。两者都能实现功能,应根据封装需求选择。

标准库的 std::abs(const std::complex<T>&) 是非成员函数,并不是 std::complex 类的友元:

问题4:工业场景中何时考虑使用 friend

只有当独立辅助函数或相关类必须直接访问多个私有成员,并且通过公开接口实现会破坏封装或造成明显开销时,才考虑使用 friend。一般应优先使用公开成员函数,友元关系应少而职责明确。


三、实验任务3

3861774-20261117223004565-2026350105

问题:const 成员函数为什么能修改 total_cnt

接口为:

void execute(ControlType cmd) const;

其中 const 限制的是该成员函数不能修改当前对象的非静态数据成员,即不能修改 *this 的状态。

total_cnt 是 static 成员,属于整个类而不是某一个 PlayerControl 对象。它不属于 const 对象 *this 的实例状态,因此即使 execute() 是 const 成员函数,也可以修改它。

选做:使用 emoji 输出

不需要修改类接口,只需修改 execute() 中 switch 的打印字符串,例如:

case ControlType::Play:
    std::cout << "▶️ Playing music...\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;

四、实验任务4

3861643-20261118002833970-1733363246

问题:分数运算函数采用哪种设计方案及理由

本实验采用 方案1:分数类 + 友元函数。

理由是:

  • output()、add()、sub()、mul()、div() 与分数类的内部表示关系紧密;
  • 友元函数可以直接访问约分后的分子和分母,减少 get_up()、get_down() 的重复调用;
  • 实现较简洁,也便于统一进行约分和分母检查。

本次实验完成了四个递进的小型类设计。通过类 T,我观察到普通构造、复制构造、移动构造和析构函数的实际调用顺序,也理解了对象生命周期与 static 计数的关系。Complex 实验说明了 const 对象只能调用 const 成员函数,以及运算符重载如何把函数调用写得更接近数学表达式。

PlayerControl 实验表明,const 成员函数保护的是对象自身的非静态成员,静态成员仍可修改。Fraction 实验则把数据归一化、异常检查、友元函数和多文件组织结合起来。总体上,封装不仅是把数据设为 private,还需要合理设计公开接口、控制友元范围,并对非法状态及时抛出异常。


posted @ 2026-11-18 22:32  Guanyunhai  阅读(3)  评论(0)    收藏  举报