实验二

实验一

源文件

  • 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.问题一:
普通构造函数 T(int x = 0, int y = 0):按给定初值创建对象,定义新对象且不用 已有对象初始化时调用。程序中 T t1;、T t2(3, 4); 各触发一次。
复制构造函数 T(const T &t):用已有对象的值初始化新对象,T t3(t2); 触发。
移动构造函数 T(T &&t):接管右值对象的资源以避免拷贝,T t4(std::move(t2)); 触发。
析构函数 ~T():对象生命周期结束时自动释放资源,离开 test() 内层花括号时连续调用四次。

2.问题三:
作用域:t1~t4 定义在 test() 函数内层花括号中,作用域为该花括号内部。
生命周期:从定义处开始,到花括号结束为止,结束后按定义逆序(t4、t3、t2、t1)依次析构,计数由 4 变为 0。
私有成员访问:不能通过 t1 访问 m1、m2。二者为 private 成员,仅类的成员函数与友元可访问,这体现类的封装特性。

3.问题四:
image
现象:程序不能正常结束,创建 t3 时异常终止,无 return value 0,无析构输出,t1、t2 未被正常销毁。
原因:t1、t2 创建后计数为 2,达到 MAX_CNT,T t3(t2) 触发构造函数中的 throw std::runtime_error。
后果:main 中无 try...catch 捕获,异常未被处理,程序调用 terminate 强制终止,栈展开不发生,已构造对象的析构函数不执行,计数不归零。

4.问题二
image
结果:编译失败。报错 multiple definition of 'T::doc'、'T::MAX_CNT'、'T::current_cnt',ld returned 1 exit status。

原因:t.h 被 t.cpp 和 task1.cpp 各包含一次,三行定义被复制成两份,链接时同名变量存在多个定义,链接器无法确定使用哪一份,故报重复定义。

结论:static 数据成员应在类内声明、在唯一一个 .cpp 文件中定义;头文件会被多个编译单元重复包含,只能放声明。

实验二

源文件

  • Complex.cpp源码
#include "Complex.h"

#include <iostream>
#include <cmath>

// static member: declared in class, defined here
const std::string Complex::doc{"a simplified complex class"};

Complex::Complex(double r, double i) : real_{r}, imag_{i} {
}

Complex::Complex(const Complex &c) : real_{c.real_}, imag_{c.imag_} {
}

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

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

void Complex::add(const Complex &c) {
    real_ += c.real_;
    imag_ += c.imag_;
}

void output(const Complex &c) {
    std::cout << c.real_ << " + " << c.imag_ << "i";
}

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

Complex add(const Complex &c1, const Complex &c2) {
    Complex sum(c1.real_ + c2.real_, c1.imag_ + c2.imag_);
    return sum;
}

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

bool is_not_equal(const Complex &c1, const Complex &c2) {
    return !is_equal(c1, c2);
}
  • Complex.h源码
#pragma once

#include <string>

class Complex {
public:
    static const std::string doc;   // class description

    Complex(double r = 0, double i = 0);   // normal constructor
    Complex(const Complex &c);             // copy constructor

    double real() const;   // get real part
    double imag() const;   // get imaginary part
    void add(const Complex &c);   // c1.add(c2) equals c1 += c2

    friend void output(const Complex &c);      // print as a + bi
    friend double abs(const Complex &c);       // modulus
    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 real_;   // real part
    double imag_;   // imaginary part
};
  • task2.cpp
// 测试标准库类模板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

回答问题

1.问题一
① 必须加 const(double real() const;)。const 对象只能调用 const 成员函数;不加则报错 discards qualifiers。

② 不能编译通过。add() 会修改成员数据,未加 const,const 对象 c6 不允许调用,报错同上。这体现类的 const 保护机制:const 对象的数据只读,由编译器强制检查。

2.问题二
标准库 std::complex 更简洁。接口一一对应:c1.add(c2) ↔ c1 += c2,add(c2,c3) ↔ c2 + c3,is_equal ↔ ==,output ↔ <<。说明运算符本质是函数,重载只是把函数调用换成更接近数学的写法,两者可互相转换。

3.问题三
① 不是必须的。不用 friend 时,改为提供公有 real()、imag() 访问函数,普通非成员函数通过它们读写数据即可实现相同功能。差异:友元直接访问私有成员,破坏封装但写法直接;接口方案封装性更好。

实验三

源码

  • 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 = control_str;
    std::transform(s.begin(), s.end(), s.begin(),
                   [](unsigned char ch) { return std::tolower(ch); });

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

回答问题

1.total_cnt 是 static 静态成员,属于类而非对象,不占用对象存储空间;const 只限制修改对象的非静态成员,故 const 成员函数 execute() 中可以对其执行 ++total_cnt。这保证了该类所有对象的操作次数统一累计。

实验四

源代码

  • Fraction.cpp代码
#include "Fraction.h"

#include <iostream>
#include <stdexcept>
#include <cmath>

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

// internal helper: greatest common divisor (a, b >= 0)
static int my_gcd(int a, int b) {
    if (b == 0) return a;
    return my_gcd(b, a % b);
}

Fraction::Fraction(int up0, int down0) : up{up0}, down{down0} {
    if (down == 0) {
        throw std::invalid_argument("Fraction: 分母不能为0");
    }
    reduce();
}

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

// normalize: always keep down > 0, sign on up, and reduced form
void Fraction::reduce() {
    int g = my_gcd(std::abs(up), std::abs(down));
    if (g > 0) {
        up /= g;
        down /= g;
    }
    if (down < 0) {
        up = -up;
        down = -down;
    }
}

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) {
    // if f2.up == 0, the constructed denominator is 0 and the constructor throws
    return Fraction(f1.up * f2.down, f1.down * f2.up);
}
  • Fraction.h代码
#pragma once

#include <string>

class Fraction {
public:
    static const std::string doc;   // class description

    Fraction(int up0 = 0, int down0 = 1);   // normal constructor, down0 == 0 throws
    Fraction(const Fraction &f);            // copy constructor

    int get_up() const;        // return numerator
    int get_down() const;      // return denominator
    Fraction negative() const; // return the negated copy, *this unchanged

    friend void output(const Fraction &f);   // print as up or up/down
    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;     // numerator, sign carried here
    int down;   // denominator, always positive after reduce()

    void reduce();   // internal helper: reduce and normalize sign
};
  • task4
#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:分数类 + 友元函数。output/add/sub/mul/div 需直接访问两个分数对象的 up、down 参与运算,做友元最直接,且声明集中在类内、接口清晰;本任务类规模小、耦合固定,封装代价可控。方案2(命名空间自由函数 + 公有接口)封装性更好,但接口暴露面更大、多一层调用,本任务无此必要。

总结

这次实验让我真正上手写了多文件项目:头文件放声明、.cpp 放实现,static 成员定义只能写在一个 .cpp 里。通过 t 类的代码,我分清了四种构造/析构函数的调用时机;自己设计 Complex、PlayerControl、Fraction 三个类时,也体会到 const 和友元不是随便加的,而是有明确用途。印象最深的是构造函数里抛异常会让程序直接崩溃、已创建的对象不析构,这块还得加强学习。

posted @ 2026-11-19 21:53  zhouyuu_stone  阅读(3)  评论(0)    收藏  举报