实验2

任务一

一、源代码

//t.cpp

#include "t.hpp"

#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 << ")";
}
//t.hpp

#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;
};
//task1.cpp

#include <iostream>
#include <utility>
#include "t.hpp"

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) :初始化新对象,在创建对象时调用。

(2)复制构造 T(const T &t) :初始化新对象;当用已存在的对象通过拷贝的方式进行初始化时调用。

(3)移动构造函数 T(T &&t):用右值t初始化新对象时调用。

(4)析构函数 ~T() :销毁对象,释放内存;当对象的生命周期结束、delete、程序结束时.

T t1; 普通构造函数(使用默认参数 0, 0)。

T t2(3, 4); 普通构造函数。

T t3(t2); 复制构造函数(用 t2 拷贝构造 t3)。

T t4(std::move(t2)); 移动构造函数(将 t2 转为右值,用来构造 t4)。

问题二:

不能正确编译

image

反思:头文件t.h会被t.cpp和task.cpp同时包含,报错原因是重复定义。

问题三:

作用域:t1、t2、t3、t4 定义在 test 函数内部的一对大括号 {} 形成的块作用域中;不能,封装性。

问题四:

throw 用来抛出异常

image

程序崩溃了。会被正常销毁:AI给的理由是C++ 标准规定,当抛出异常且沿着调用栈向上做栈展开(stack unwinding)时,会自动销毁已经构造完成、还没有析构的自动局部对象,按构造相反顺序调用它们的析构函数;t3 构造中途抛异常,t3 本身不算构造成功,不会调用 t3 的析构函数。

任务2

一、源代码


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

// Complex.cpp
//Complex.cpp
#include <iomanip>
#include <iostream>
#include "Complex.h"
using namespace std;
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_}{}
void Complex::add(Complex c){
	real_+=c.real_;
	imag_+=c.imag_;
}
double Complex::real() const{
	return real_;
}
double Complex::imag() const{
	return imag_;
}
void output(const Complex& c){
	cout << c.real_ << "+" << c.imag_ << "i\n";
}
double abs(const Complex& c){
	return sqrt(c.real_*c.real_+c.imag_*c.imag_);
}
Complex add(Complex c1,Complex c2){
	Complex c3;
	c3.real_ = c1.real_ + c2.real_;
	c3.imag_ = c1.imag_ + c2.imag_;
	return c3;
}
bool is_equal(Complex c1,Complex c2){
	if(c1.real_==c2.real_&& c1.imag_ == c2.imag_) return true;
	return false;
}
bool is_not_equal(Complex c1,Complex c2){
	return (!is_equal(c1,c2));
}
// Complex.h
//Complex.h
#pragma once
#include <cmath>
#include <string>

using namespace std;

class Complex{
public:
	static const std::string doc;
	Complex(double r = 0.0,double i = 0.0);
	Complex(const Complex& c);
	double real() const;
	double imag() const;
	void add(Complex c);
	friend void output(const Complex& c);
	friend double abs(const Complex& c);
	friend Complex add(Complex c1,Complex c2);
	friend bool is_equal(Complex c1,Complex c2);
	friend bool is_not_equal(Complex c1,Complex c2);
private:
	double real_;
	double imag_;
};

二、运行截图

image

三、问题回答:

问题1:必须加上const,不加的话会报错,报错信息如下

image

不能。因为c6是constconst 对象,而 add 是会修改对象。体现了类的 const 保护机制,保证了 const 的对象在初始化后不能被修改。

问题2:标准库模板类更加简洁,标准库将相关运算进行封装,让代码简洁,直观的输出结果。

问题3:std::abs是<complex>中的非成员函数模板,并非std::complex的成员或友元,它调用类的公有接口real()、imag()获取实部虚部完成模长计算,无需友元即可实现功能。工程实践中友元仅在必须访问私有成员且不宜增设公有接口时才使用,因其会破坏封装,应当尽量少用。 参考:https://en.cppreference.com/w/cpp/numeric/complex/abs

任务3

一、源代码

//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();
}
//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 <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 str = control_str;//不能是空的 
    std::transform(control_str.begin(), control_str.end(),str.begin(),[](unsigned char c){return tolower(c);});//不能直接传给tolower 
	if(str=="play") return ControlType::Play;
	if(str=="pause") return ControlType::Pause;
	if(str=="next") return ControlType::Next;
	if(str=="prev") return ControlType::Prev;
	if(str=="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;
}

二、运行截图

image

三、问题回答:

1.因为total_cnt是静态成员变量。const 成员函数仅仅限制修改属于本对象的普通成员,它是把this指针变成常量指针,不让通过this修改对象自身的数据。但静态成员不属于任何一个对象,不存放在对象内存里,访问它也不需要依靠this指针,所以在 const 成员函数里依旧可以修改静态成员total_cnt。

任务4

一、源代码

//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();
}
//Fraction.h
#pragma once
#include <string>

class Fraction {
public:
	//类属性 
    static const std::string doc;
    
	//构造函数  
    Fraction(int up = 0, int down = 1);
    Fraction(const Fraction& f);
    
	//接口 
    int get_up() const;
    int get_down() const; 
    Fraction negative() const;

    //友元工具函数 
    friend void output(const Fraction& f);
    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);
	
	//化简
	void simplify(); 
private:
    int up;
    int down;
};
//Fraction.cpp
#include "Fraction.h"
#include <iostream>
#include <stdexcept>
#include <cmath>

using namespace std;

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

//构造函数 
Fraction::Fraction(int up0, int down0) : up(up0), down(down0) {
    if (down == 0) {
        throw invalid_argument("Fraction: 分母不能为0");
    }
    simplify(); //构造时立刻化简
}
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; }
Fraction Fraction::negative() const {
    return Fraction(-up, down);
}

//工友元工具函数  
//PS:用引用传效率更高,后同 
void output(const Fraction& f) {
    //如果分母为1,直接输出分子
    if (f.down == 1) {
        cout << f.up;
    } else {
        cout << f.up << "/" << f.down;
    }
}

//加 (a/b + c/d = (ad+bc)/bd) 
Fraction add(const Fraction& f1, const Fraction& f2) {
    return Fraction(f1.up * f2.down + f2.up * f1.down, f1.down * f2.down);
}

//减 (a/b - c/d = (ad-bc)/bd) 
Fraction sub(const Fraction& f1, const Fraction& f2) {
    return Fraction(f1.up * f2.down - f2.up * f1.down, f1.down * f2.down);
}

//乘 (a/b * c/d = ac/bd)
Fraction mul(const Fraction& f1, const Fraction& f2) {
    return Fraction(f1.up * f2.up, f1.down * f2.down);
}

//除 (a/b / c/d = ad/bc)
Fraction div(const Fraction& f1, const Fraction& f2) {
    if (f2.up == 0) {//因为 b和 d既然构造出来就肯定不会是 0了 ,所以只需检查 c 
        throw std::invalid_argument("Fraction: 分母不能为0");
    }
    return Fraction(f1.up * f2.down, f1.down * f2.up);
}
//递归 
int gcd(int a, int b) {
    if(b == 0) return a;
    else return gcd(b, a%b);
}
//化简分数、处理符号
void Fraction::simplify() {
    if(up == 0) {
        down = 1;//因为当分母为 1时,会直接输出分子 
        return;
    }
    //符号都放在分子上
    if(down < 0) {
        up = -up;
        down = -down;
    }
    int g = gcd(abs(up), abs(down));//求最大公因子 
    up /= g;
    down /= g;
}

二、运行截图

image

三、问题回答:

我打算选用友元函数来实现 output、add、sub、mul、div。

如果不用友元,要么就得写一堆 get 函数拿分子分母,写起来比较麻烦;要是直接把 up、down 改成 public,内部数据就全部暴露了,封装就没了。用了友元之后我可以直接读到私有成员 up 和 down,写四则运算代码会简单不少。而且题目给的测试代码就是 add(f1,f2)、output(f1) 这种普通函数调用,不用改成类域调用,原来的测试代码可以直接跑,不用大改。加上我之前练习过友元,语法相对熟一点,写代码、找 bug 会轻松些。

不过我也知道友元有缺点,它相当于放开了私有成员的访问权限,会一定程度破坏封装。计算出来的新分数,我交给构造函数统一处理约分和分母符号。

 

 

五、反思总结

1.一些问题我还是需要依靠ai来解决,我觉得依靠ai是大势所趋,但是不是完全的让ai来代替我们的思考,而是让ai来促进我们的思考,增强我们学习的效率

posted @ 2026-11-19 23:59  yyyyy_0617  阅读(0)  评论(0)    收藏  举报