实验2
实验任务1
源代码:
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 //友元函数不是T类成员函数,被授权访问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>//std::runtime_error实际在此处用到,用于预定义的异常类 #include <string> // static成员数据: 类内声明、类外初始化 const std::string T::doc{ "a simple class sample" };//static类外定义要加类名T:: 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) {//按ratio调整放大倍数 m1 *= ratio; m2 *= ratio; } // 类方法:属于类本身,不依赖对象直接调用,内部无this指针,只能访问static成员 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:
普通构造函数 T(int x = 0, int y = 0):用于初始化对象,在创建对象时调用。
复制构造函数 T(const T &t):用已存在的对象初始化新对象时调用(拷贝数据)。
移动构造函数 T(T &&t):用右值t初始化新对象时调用。
析构函数 ~T():在对象生命周期结束(离开作用域、被 delete 等)时自动调用。
T t1; 普通构造函数(使用默认参数 0, 0)。
T t2(3, 4); 普通构造函数。
T t3(t2); 复制构造函数(用 t2 拷贝构造 t3)。
T t4(std::move(t2)); 移动构造函数(将 t2 转为右值,用来构造 t4)。
问题2:
不能正确编译

原因分析:头文件 t.h 会被 t.cpp 和 task1.cpp 同时 #include,所以报错信息是重复定义。
问题3:
从创建对象到test结束。不能,体现了类的封装性。
问题4:throw用于抛出异常。

程序崩溃,中断了,没有调用析构,不会被销毁。
实验任务2
源代码:
Complex.h
#pragma once #include<string> class Complex { public: static const std::string doc; Complex(double r = 0, double i = 0); Complex(const Complex& c) = default; 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_part; double imag_part; };
Complex.cpp
#include "Complex.h" #include<iostream> #include<cmath> const std::string Complex::doc = "a simplified Complex class"; Complex::Complex(double r , double i ):real_part(r),imag_part(i){} double Complex::real() const { return real_part; } double Complex::imag() const { return imag_part; } void Complex::add(const Complex& c) { real_part += c.real_part; imag_part += c.imag_part; } void output(const Complex& c) { std::cout << c.real_part; if (c.imag_part >= 0) std::cout << "+" << c.imag_part << "i"; else std::cout << "-" << -c.imag_part << "i"; } double abs(const Complex& c) { return std::sqrt(c.real_part * c.real_part + c.imag_part * c.imag_part); } Complex add(const Complex& c1, const Complex& c2) { return Complex(c1.real_part + c2.real_part, c1.imag_part + c2.imag_part); } bool is_equal(const Complex& c1, const Complex& c2) { return (c1.real_part == c2.real_part) && (c1.imag_part == c2.imag_part); } bool is_not_equal(const Complex& c1, const Complex& c2) { return !is_equal(c1, c2); }
task2:
#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(); }
运行结果:

问题回答:
问题1:
1.加上const,c6是const对象,如果删掉const,其权限放大不能用。
2.不能通过,const对象只能调用const成员函数,体现了常量保护机制。

问题2:
标准库模板类更加简洁,标准库将相关运算进行封装,让代码简洁,直观的输出结果。
问题3:
1.不是,友元函数的作用就是方便调用Complex类内成员,如果用普通成员函数比如下面要执行四次函数
Complex add(const Complex& c1, const Complex& c2) { return Complex(c1.real() + c2.real(), c1.imag() + c2.imag()); }
2.
我觉得可以用在封装性不是很重要的地方,比如只是做简单计算(像复数、分数这种本身数据就很透明的类)。反正数据被看到了也不会出什么大问题,直接用 friend 少写一堆 get 接口(real(),image()等),代码写起来更简洁。但如果是复杂系统,乱开后门容易出事故,那就坚决不用。
实验任务3
源代码
PlayerControl.h
#pragma once #include <string> enum class ControlType { Play, Pause, Next, Prev, Stop, Unknown };//enum枚举类型 class PlayerControl { public: PlayerControl();//默认构造函数 //parse:解析,将输入字符串转化成enum里的成员 ControlType parse(const std::string& control_str); // 实现std::string --> ControlType转换 void execute(ControlType cmd) const; // 执行控制操作(以打印输出模拟) static int get_cnt(); private: static int total_cnt;//执行一次execute加一 };
PlayerControl.cpp
#include "PlayerControl.h" #include <algorithm> #include <iostream>
#include <cctype> 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 lower_str = control_str; for (char& c : lower_str) { c = std::tolower(c); } if (lower_str == "play") return ControlType::Play; if (lower_str == "pause") return ControlType::Pause; if (lower_str == "next") return ControlType::Next; if (lower_str == "prev") return ControlType::Prev; if (lower_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; }
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(); }
运行结果:

问题回答:
因为 total_cnt 是类的 static 静态成员变量。const 成员函数保证不修改this指针指向的内容,但是,静态成员变量属于整个类,没有 this 指针。因此,const 成员函数内部是完全允许修改类的静态成员变量的。不能修改controller对象里的非静态成员。
PlayerControl.cpp
#include "PlayerControl.h" #include <algorithm> #include <iostream> #include <cctype> 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 lower_str = control_str; for (char& c : lower_str) { c = std::tolower(c); } if (lower_str == "play") return ControlType::Play; if (lower_str == "pause") return ControlType::Pause; if (lower_str == "next") return ControlType::Next; if (lower_str == "prev") return ControlType::Prev; if (lower_str == "stop") return ControlType::Stop; return ControlType::Unknown; } void PlayerControl::execute(ControlType cmd) const { ++total_cnt; switch (cmd) { case ControlType::Play: std::cout << "🎵 Playing music...\n"; break; case ControlType::Pause: std::cout << "⏸Music paused\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; 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(); }
运行结果:

Emoji 选做尝试(AI 辅助排错)
实验任务4
源代码:
Fraction.h
#pragma once #include<string> class Fraction { public: static const std::string doc; Fraction(int up0=0,int down0=1);//构造函数 Fraction(const Fraction& f) = default;//复制构造函数 int get_up() const;//get接口 int get_down() const;//get接口 Fraction negative() const;//分数求负函数 friend void output(const Fraction& f);//无返回对象 friend Fraction add(const Fraction& f1, const Fraction& f2);//返回Fraction对象 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; int down; void simplify(); };
Fraction.cpp
#include "Fraction.h" #include<stdexcept>//定义标准异常类 #include<iostream> #include<cmath> const std::string Fraction::doc="Fraction类 v 0.01版.\n""目前仅支持分数对象的构造、输出、加/减/乘/除运算."; static int gcd(int a, int b) {//静态函数只在当前cpp中被利用 a = std::abs(a); b = std::abs(b); while (b != 0) { int t = b; b= a % b; a = t; } return a; } Fraction::Fraction(int up0, int down0) :up{ up0 }, down{ down0 } {//构造函数 if (down == 0) { throw std::invalid_argument("Fraction: 分母不能为0");//std::invalid_argument 是 C++ 标准库(在 <stdexcept> 头文件里)提供的一个专门用来表示“参数不合法”的异常类。 } simplify(); // 构造时立刻化简 } void Fraction::simplify() { //统一符号符号放在分子上面 if (down < 0) { up = -up; down = -down; } //分子为0,分母为1 if (up == 0) { down = 1; } //约分 int m = gcd(up, down); up /= m; down /= m; } 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) { int new_up = f1.up * f2.down + f2.up * f1.down; int new_down = f1.down * f2.down; return Fraction(new_up, new_down); } Fraction sub(const Fraction& f1, const Fraction& f2) { int new_up = f1.up * f2.down - f2.up * f1.down; int new_down = f1.down * f2.down; return Fraction(new_up, new_down); } Fraction mul(const Fraction& f1, const Fraction& f2){ int new_up = f1.up * f2.up; int new_down = f1.down * f2.down; return Fraction(new_up, new_down); } Fraction div(const Fraction& f1, const Fraction& f2) { int new_up = f1.up * f2.down; int new_down = f1.down * f2.up; return Fraction(new_up, new_down); }
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 = "; // 【修改点】:加入 try-catch 捕获异常:尝试(try)执行一段可能会出错的代码,如果出错了,就捕获(catch)这个错误并妥善处理,而不是让程序直接崩溃 try { output(div(f6, f7)); } catch (const std::invalid_argument& e) { cout << "terminate called after throwing an instance of 'std::invalid_argument'" << endl; cout << " what(): " << e.what() << endl; } cout << endl; } int main() { std::cout << "测试1: Fraction类基础功能测试\n"; test1(); std::cout << "\n测试2: 分母为0测试: \n"; test2(); }
运行结果:



问题回答:
我选择了方案 1(分数类 + 友元函数)。在类内声明 friend,在 .cpp 中以非成员函数形式实现。这样既保证了外部函数能高效访问类的私有数据成员(分子 up 和分母 down),又保持了代码结构的清晰。
在第一次测试“分母为0”的情况时,当执行到 f6 / f7 = 时,控制台程序并未正常输出预期的异常提示信息,而是直接闪退(或卡死中断),导致后续内容无法正常打印。解决方式:应该在被调用的外层(比如 test2 函数中)使用 try-catch 语句块捕获异常,这样程序不仅不会崩溃,还能由程序员自定义错误提示输出,提高程序的健壮性。
实验总结:
任务1了解到普通构造、复制构造、移动构造、析构函数分别在什么时机被调用。任务 2友元可用公有接口替代。任务 3static 静态成员属于类而非对象,所以 const 函数里才能修改 total_cnt。任务 4 的分数类我了解到throw 抛异常处理分母为 0 的情况,在ai工具辅助下成功运行出结果。
浙公网安备 33010602011771号