实验二

实验2 类和对象_基础编程1

任务一 简单类 T:封装 / static / friend / const

源代码

点击查看代码(t.h / t.cpp / task1.cpp)

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

运行截图

屏幕截图 2026-11-17 221907

问题

1. 构造函数、析构函数的功能与调用时机

  • T(int x = 0, int y = 0) 普通构造:创建对象时初始化 m1、m2,对象计数 +1 并检查上限 → t1、t2 触发
  • T(const T &) 复制构造:用已存在的同类对象初始化新对象(含按值传参、按值返回)→ t3 触发
  • T(T &&) 移动构造:用右值 / std::move 初始化新对象,直接接管数据、不做深复制 → t4 触发
  • ~T() 析构:对象生命期结束时自动调用,计数 -1;内层作用域结束时按 t4→t1 逆序各调用一次

2. 静态成员定义移到 t.h 末尾:不能编译通过

链接期报错 multiple definition of 'T::doc' … ld returned 1 exit status。原因是 t.h 被 t.cpp、task1.cpp 各包含一次,静态成员的定义就出现在两个 .o 中,违反单一定义规则(ODR)。正确做法是类内声明、类外定义,定义只写在一个 .cpp 里。

屏幕截图 2026-11-18 134232

3. t1–t4 的作用域与生命期

  • 作用域:都定义在 test() 内层 { } 中,仅该块内可见
  • 生命期:构造完成开始,离开右花括号结束,逆序析构 t4→t1
  • 不能通过 t1 访问 m1、m2:private 只对本类成员函数和友元开放,t1.m1 会编译报错(is private within this context),测试只能经 get_cnt()、output(t1) 间接访问
  • 体现封装:数据隐藏 + 访问权限控制,接口与实现分离

4. throw 的作用;MAX_CNT 改为 2 的后果

throw 抛出异常对象,终止当前函数流程并沿调用链寻找匹配的 catch;无处理者时调用 std::terminate()(进而 abort)结束程序。

改为 2 后:t1、t2 构造完成后,构造 t3 时抛出 runtime_error → terminate called after throwing an instance of 'std::runtime_error',程序崩溃,不是正常结束。

已创建的对象不会被销毁:异常未被捕获,abort 立即终止进程、不做栈展开,t1、t2 的析构函数不会执行(实测输出中一条 destructor 都没有);t3 构造未完成,也不计入对象数、不析构。

任务二 简化复数类 Complex

源代码

点击查看代码(Complex.h / Complex.cpp / task2.cpp)

Complex.h

#pragma once

#include <string>

// 简化版复数类
class Complex {
public:
    // 构造函数:缺省参数同时支持 Complex()、Complex(3.5)、Complex(3, -4)
    Complex(double r = 0.0, double i = 0.0);
    // 复制构造函数
    Complex(const Complex &c);

    // 接口:返回实部、虚部(const成员函数,可被const对象调用)
    double real() const;
    double imag() const;

    // 把另一个复数 c 加到自身,相当于 c1 += c2
    void add(const Complex &c);

public:
    // 类属性:类说明信息
    static const std::string doc;

    // 友元:输出、取模、求和、比较
    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);

private:
    double m_real;   // 实部
    double m_imag;   // 虚部
};

Complex.cpp

#include "Complex.h"

#include <cmath>
#include <iostream>

// static成员数据:类内声明、类外初始化
const std::string Complex::doc{"a simplified complex class"};

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

Complex::Complex(const Complex &c): m_real{c.m_real}, m_imag{c.m_imag} {}

// const成员函数:不修改对象数据成员,const对象/const引用才能调用
double Complex::real() const {
    return m_real;
}

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

// this指针指向调用该方法的对象,形参用const引用保护实参
void Complex::add(const Complex &c) {
    m_real += c.m_real;
    m_imag += c.m_imag;
}

// 友元:以 a+bi 的形式输出,如 3+4i、3-4i
void output(const Complex &c) {
    std::cout << c.m_real;
    if(c.m_imag >= 0)
        std::cout << "+";
    std::cout << c.m_imag << "i";
}

// 友元:复数取模 |a+bi| = sqrt(a^2 + b^2)
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();
}

运行截图

屏幕截图 2026-11-17 222253

屏幕截图 2026-11-17 222331

问题

1. ① 必须给成员函数加 const

double real() const;、double imag() const;。const 对象的 this 是 const Complex*,只能调用承诺不修改对象的 const 成员函数;不加则报 error: passing 'const Complex' as 'this' argument discards qualifiers。

② c6.add(c2); 编译不通过

add() 要修改数据,是非 const 成员函数,对 const 对象调用同样报 discards qualifiers。这体现 const 保护机制:const 对象 + const 成员函数 + const 引用形参,由编译器在编译期做只读检查,零运行时开销。

2. 用法对比:std::complex 更简洁

自定义类 Complex 标准库 std::complex<T>
c1.add(c2) c1 += c2
c4 = add(c2, c3) c4 = c2 + c3
is_equal(c1, c2) / is_not_equal(c1, c2) c1 == c2 / c1 != c2
output(c1) / abs(c2) cout << c1 / abs(c2)

说明函数与运算存在内在关联:运算符本质是函数调用的另一种写法(a + b 即 operator+(a, b))。运算符重载把函数调用映射成数学表达式,让自定义类型获得与内置类型一致的表达,可读性、可维护性都更好。

3. ① output / abs / add 必须是友元吗?

不必。用公有接口即可实现:output 用 real()/imag() 拼字符串;abs 用 sqrt(real()² + imag()²);add 用 Complex r(c1.real() + c2.real(), c1.imag() + c2.imag())。friend 只是省去 getter、少一层调用,代价是封装被局部突破、函数与内部表示耦合;内部表示易变时应优先用公有接口。

② std::complex 的 abs 不是友元:它是 std 命名空间里的非成员函数(std::abs 重载),通过 real()、imag() 实现。

③ 何时考虑 friend(≤150 字)

当外部函数/类必须直接访问内部表示才能高效、自然地实现时:运算符重载(operator<<、operator+)、紧密协作的一对类(容器与迭代器)、构造私有构造函数的工厂函数、需同时访问两个对象私有数据的函数。friend 会削弱封装、增加耦合,能用公有接口实现时优先不用。

任务三 播放器控制类 PlayerControl

源代码

点击查看代码(PlayerControl.h / PlayerControl.cpp / task3.cpp)

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 s;
    s.reserve(control_str.size());
    for(auto c : control_str)
        s += static_cast<char>(std::tolower(static_cast<unsigned char>(c)));

    if(s == "play")  return ControlType::Play;
    if(s == "pause") return ControlType::Pause;
    if(s == "next")  return ControlType::Next;
    if(s == "prev")  return ControlType::Prev;
    if(s == "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();
}

运行截图

屏幕截图 2026-11-17 222949

问题

const 成员函数里为什么允许 ++total_cnt?

total_cnt 是 static 成员,属于类本身而不是某个对象,不在 this 所指对象内部。const 成员函数只承诺不修改对象的数据成员,静态成员不受这条限制,因此可以自增。反例:若它是普通非静态成员,在 const 函数里 ++total_cnt 会报 assignment of member 'total_cnt' in read-only object。

选做:输出 emoji

不用改枚举、parse 和计数,只把 execute() 各分支的提示串换成 emoji(如 ▶️ 正在播放…);源文件存 UTF-8,Windows 控制台加 SetConsoleOutputCP(CP_UTF8)(或运行前 chcp 65001),并用支持彩色 emoji 的终端(Windows Terminal)。

任务四 分数类 Fraction

源代码

点击查看代码(Fraction.h / Fraction.cpp / task4.cpp)

Fraction.h

#pragma once

#include <string>

// 分数类:方案1  分数类 + 友元函数
class Fraction {
public:
    // 构造函数:Fraction(2) → 2/1;Fraction(2, -3) → -2/3
    Fraction(int up0 = 0, int down0 = 1);
    // 复制构造函数
    Fraction(const Fraction &f);

    // 接口:返回分子、分母
    int get_up() const;
    int get_down() const;

    // 求负:自身不变,返回求负后的新对象
    Fraction negative() const;

public:
    // 类属性:类说明信息
    static const std::string doc;

    // 友元:输出与四则运算
    friend void output(const Fraction &f);
    friend Fraction add(const Fraction &a, const Fraction &b);
    friend Fraction sub(const Fraction &a, const Fraction &b);
    friend Fraction mul(const Fraction &a, const Fraction &b);
    friend Fraction div(const Fraction &a, const Fraction &b);

private:
    int up;     // 分子
    int down;   // 分母,恒正
    void normalize();   // 内部工具函数:约分并统一符号
};

Fraction.cpp

#include "Fraction.h"

#include <iostream>
#include <numeric>
#include <stdexcept>

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

    normalize();
}

Fraction::Fraction(const Fraction &f): up{f.up}, down{f.down} {}

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

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

// 内部工具函数:符号统一到分子、按最大公约数约分
void Fraction::normalize() {
    if(down < 0) {      // 分母恒为正
        up = -up;
        down = -down;
    }

    if(up == 0) {       // 0/n 统一表示成 0/1
        down = 1;
        return;
    }

    int g = std::gcd(up < 0 ? -up : up, down);
    up /= g;
    down /= g;
}

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

// 友元:输出化简后的形式,如 2/3、-2/3
void output(const Fraction &f) {
    std::cout << f.up << "/" << f.down;
}

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

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

Fraction mul(const Fraction &a, const Fraction &b) {
    return Fraction(a.up * b.up, a.down * b.down);
}

Fraction div(const Fraction &a, const Fraction &b) {
    return Fraction(a.up * b.down, a.down * b.up);   // b.up 为0时分母为0,抛异常
}

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

运行截图

屏幕截图 2026-11-18 133438

问题

方案选择:方案1 分数类 + 友元函数

  1. 运算要读写 up、down 并维持“分母恒正、已约分”的不变式;友元直接访问私有数据,不必开放能破坏不变式的 setter,公有接口更少更安全
  2. 调用形式 output(f1)、add(f1, f2) 与给定 task4.cpp 完全一致,测试代码零改动(方案2 要加 frac:: 前缀)
  3. 运算集中在 Fraction.cpp,私有工具函数 normalize() 统一约分与符号,代码短、不会漏约分

代价是 friend 突破封装,但分数运算与内部表示天然强相关,耦合是局部可控的。

分母为 0 的处理:构造函数是唯一入口,down == 0 时直接 throw std::invalid_argument("Fraction: 分母不能为0"),故 add/sub/mul/div 自动受保护;测试2 中 f6 / f7 因 f7 的分子为 0 使结果分母为 0,异常未捕获 → terminate,符合“错误尽早暴露”的设计。

总结

本次实验完成了四件事:用多文件结构实现并测试简单类 T、设计简化复数类 Complex、实现播放器控制类 PlayerControl、实现支持四则运算的分数类 Fraction。做完之后,类、对象、封装、构造/析构、static、friend、const 这些概念从“知道语法”变成了“知道为什么这样设计”。

最核心的体会是“同一份数据,不同的共享与保护策略”:对象内部数据在自己的成员函数间共享,于是有 private + 公有接口;同类所有对象共享计数,于是有 static 成员;外部函数要参与运算又不破坏封装边界,于是有 friend。反过来,const 对象、const 引用形参、const 成员函数构成只读一侧的保护,把错误挡在编译期。

调试中最深的几个细节:静态成员数据写进头文件会在链接期报 multiple definition;const 对象只能调用 const 成员函数,忘了加 const 报 discards qualifiers;static 成员不受 const 只读限制;未捕获的异常会直接 terminate、不展开栈,析构函数不执行。可以改进的地方:Fraction 用 int 存储易溢出,可改 long long;Complex 可补上 +=、==、<< 运算符重载;PlayerControl 的 parse 可用 std::map 消除重复比较。后续会继续把“能跑通”提升到“设计合理、接口好用”。

posted @ 2026-11-18 13:43  qymqym  阅读(7)  评论(0)    收藏  举报