实验2

task1

源代码

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

运行结果截图

image

回答问题

问题1:
通过查阅教材,ai补充:
普通构造函数:在创建对象时进行初始化。在对象被创建时调用。
复制构造函数:使一个已经存在的对象,去初始化同类的一个新对象。在对象被拷贝初始化时调用。
移动构造函数:通过移动而不复制实参的高性能方式构建新对象。在对象被移动初始化时,即使用右值来初始化新对象时被调用。
析构函数:用来完成对象被删除前的一些清理工作。在对象的生存期即将结束的时刻被自动调用。
t1:触发了普通构造函数
t2:触发了普通构造函数
t3:触发了复制构造函数
t4:触发了移动构造函数

问题2:
确实能跑通,但貌似不是正确的编译方式,通过询问ai,编译器把两个同名的定义自动合成了一份,这是宽容机制的作用,换成严格一点的编译器可能就会报错。

问题3:
作用域在第13行到第28行{}之间,生命期从各自被定义开始到代码执行到第28行的“}”时结束,此时调用析构函数逆序销毁(t4,t3,t2,t1)。不能,体现了类的封装性。

问题4:
throw功能:
throw 用于抛出异常,强制中断正常的代码执行流程,将错误信息传给上层调用者。如果没有 catch 捕获,程序将直接崩溃(非正常终止)。
如图,修改后程序崩溃了。
image

已经创建的对象不会被正常销毁。
从运行截图可以看出,在抛出异常并终止程序的过程中,并没有输出 T destructor called. 因为该异常没有被 try-catch 语句捕获,操作系统会直接强制结束程序(调用std::terminate)。这种“暴毙”式的退出,使得代码来不及执行正常的清理工作,导致栈上已经创建的 t1 和 t2 未能调用析构函数就被销毁了。这说明,未捕获的异常会导致内存或资源泄漏。

task2

源代码

Complex.h

#pragma once
#include <string>
#include <iostream>

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

    Complex();
    Complex(double r);
    Complex(double r, double i);
    Complex(const Complex& c);

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

    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 real_;
    double imag_;
};

Complex.cpp

#include "Complex.h"
#include <cmath>

const std::string Complex::doc = "a simplified complex class";

Complex::Complex() : real_(0), imag_(0) {}
Complex::Complex(double r) : real_(r), imag_(0) {}
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) {
    if (c.imag_ < 0) {
        std::cout << c.real_ << " - " << -c.imag_ << "i";
    } else {
        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) {
    return Complex(c1.real_ + c2.real_, c1.imag_ + c2.imag_);
}

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

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-18 231134

回答问题

问题1:
①必须加上const,不加时编译器会报错:将 const 对象当作 this 传递时丢弃了 const 限定符。
image
②不能编译通过,因为 add 成员函数会修改成员变量(real_ += ...),是非 const 成员函数,编译器禁止 const 对象调用可能修改自身状态的方法。体现了类的数据保护机制。

问题2:
标准库模板类complex更简洁,同时也更符合数学逻辑与直觉。运算符通过函数实现,利于操作者使用的运算符实现应与日常的逻辑挂钩。

问题3:
①不是必须的。可以,在类里面写好公有的get方法(如real()、imag()),然后让外面的普通函数调用这些方法来间接获取数据。
② image
image

官方网站卡在人机验证界面,故使用镜像网站查询,标准库 std::complex 并不把 abs 设为友元
③只有在必须跨类直接访问私有数据且没有低成本替代方案时,才考虑使用 friend 。一般情况下会避免使用 friend。

task3

源代码

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 = control_str;
    for (char& c : s)
        c = 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();
}

运行结果截图

image

回答问题

const 成员函数向编译器承诺的是:“绝不修改该对象自身的非静态成员变量”(即不修改 this 指针指向的数据)。
而 total_cnt 被声明为 static int,它属于整个类,而不属于某一个具体的对象。它存储在全局数据段,根本没有 this 指针。因此,修改静态成员变量不违反 const 成员函数的承诺,编译器是允许的。

task4

源代码

Fraction.h

#pragma once

#include <string>

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

    Fraction(int up0 = 0, int down0 = 1);
    Fraction(const Fraction&) = default;

    int get_up() const;
    int get_down() const;

    Fraction negative() const;

    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, down;

    void normalize();
    static int gcd(int a, int b);
};

Fraction.cpp

#include "Fraction.h"

#include <iostream>
#include <stdexcept>

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

int Fraction::gcd(int a, int b) {
    if (a < 0) a = -a;
    if (b < 0) b = -b;
    while (b != 0) {
        int t = a % b;
        a = b;
        b = t;
    }
    return a;
}

void Fraction::normalize() {
    if (down < 0) {
        up = -up;
        down = -down;
    }
    int g = gcd(up, down);
    if (g > 1) {
        up /= g;
        down /= g;
    }
}

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

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

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。这几个函数都要读 up 和 down,写成友元函数可以直接访问私有成员,不用改成 public,也不用写一堆 get 函数。而且 task4.cpp 里就是 add(f1, f2)、output(f1) 这样调的,选方案 1 测试代码不用改,如果选方案 2 就都得起加 frac::,目前友元函数已经够用。

posted @ 2026-11-19 16:54  Mon03tr  阅读(10)  评论(0)    收藏  举报