实验2
实验任务一
#pragma once #include <string> // 类T: 声明 class T { // 对象属性、方法 public: T(int x = 0, int y = 0); // 普通构造函数 T(const T &t); // 复制构造函数 T(T &&t); // 移动构造函数 ~T(); // 析构函数 void adjust(int ratio); // 按系数成倍调整数据 void display() const; // 以(m1, m2)形式显示T类对象信息 private: int m1, m2; // 类属性、方法 public: static int get_cnt(); // 显示当前T类对象总数 public: static const std::string doc; // 类T的描述信息 static const int max_cnt; // 类T对象上限 private: static int cnt; // 当前T类对象数目 // 类T友元函数声明 friend void func(); }; // 普通函数声明 void func();
#include "T.h" #include <iostream> #include <string> // 类T实现 // static成员数据类外初始化 const std::string T::doc{"a simple class sample"}; const int T::max_cnt = 999; int T::cnt = 0; // 类方法 int T::get_cnt() { return cnt; } // 对象方法 T::T(int x, int y): m1{x}, m2{y} { ++cnt; std::cout << "T constructor called.\n"; } T::T(const T &t): m1{t.m1}, m2{t.m2} { ++cnt; std::cout << "T copy constructor called.\n"; } T::T(T &&t): m1{t.m1}, m2{t.m2} { ++cnt; std::cout << "T move constructor called.\n"; } T::~T() { --cnt; std::cout << "T destructor called.\n"; } void T::adjust(int ratio) { m1 *= ratio; m2 *= ratio; } void T::display() const { std::cout << "(" << m1 << ", " << m2 << ")" ; } // 普通函数实现 void func() { T t5(42); t5.m2 = 2049; std::cout << "t5 = "; t5.display(); std::cout << '\n'; }
#include "T.h" #include <iostream> void test_T(); int main() { std::cout << "test Class T: \n"; test_T(); std::cout << "\ntest friend func: \n"; func(); } void test_T() { 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 = "; t1.display(); cout << endl; T t2(3, 4); cout << "t2 = "; t2.display(); cout << endl; T t3(t2); t3.adjust(2); cout << "t3 = "; t3.display(); cout << endl; T t4(std::move(t2)); cout << "t4 = "; t4.display(); cout << endl; cout << "test: T objects'current count: " << T::get_cnt() << endl; }

问题1:不能

友元声明只授予func函数访问T类私有成员的权限,不是函数的正式声明,它不会将func引入到当前作用域
问题2:
①功能:创建T类对象,用参数x和y初始化成员变量
调用时机:
T t1;(使用默认参数)
T t2(3, 4);(显式传参)
隐式类型转换时
②功能:用已有对象创建新对象,实现深拷贝
调用时机:
T t3 = t2;(拷贝初始化)
函数按值传参时
函数返回对象时(未优化情况)
③功能:"窃取"临时对象的资源,避免不必要的拷贝
调用时机:
T t4 = std::move(t2);(显式移动)
返回局部对象时(RVO优化失败时)
标准库容器重新分配时
④功能:释放对象占用的资源
调用时机:对象离开作用域或被delete时
问题3:
不能,静态成员变量在类内只是声明,需要在类外单独定义
实验任务二
#ifndef COMPLEX_H // 头文件保护宏:防止头文件被重复包含 #define COMPLEX_H #include <string> // 引入string类型的头文件(因为要定义doc属性) #include <iostream> // 引入输入输出头文件(因为要输出复数) using namespace std; // 使用std命名空间,简化代码(避免写std::string、std::cout) class Complex { // 定义Complex类 public: //类属性:公有静态常量doc static const string doc; //static:表示这是“类的属性”(所有Complex对象共享,不需要创建对象就能访问) //const:表示这个属性的值不能被修改 //作用:存储类的说明信息(实验要求的“类属性”) //构造函数声明(用于创建对象) Complex(double real = 0.0, double imag = 0.0); // 普通构造函数 //形参带默认值: //无参调用(Complex c1;):real=0.0、imag=0.0 → 构造0+0i //单参调用(Complex c2(3.5);):real=3.5、imag=0.0 → 构造3.5+0i //双参调用(Complex c3(3, -4);):real=3、imag=-4 → 构造3-4i Complex(const Complex& other); // 复制构造函数 //形参是“const Complex&”:表示传入一个已存在的Complex对象的“只读引用” //作用:用已有的对象构造新对象(比如Complex c4(c2); 或 Complex c5 = c2;) //接口方法声明(类的“功能函数”) double get_real() const; // 返回实部 double get_imag() const; // 返回虚部 //const:表示这个函数不会修改对象的成员变量(只读操作) void add(const Complex& other); // 自身累加另一个复数 //作用:把other的实部/虚部加到当前对象上(比如c1.add(c2) → c1 = c1 + c2) //友元函数声明(友元可以直接访问类的私有成员) friend void output(const Complex& c); // 输出复数(a+bi格式) 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); // 判断不相等 //friend:表示这些函数不是类的成员,但可以直接访问Complex的私有成员(real、imag) private: //私有成员:只有类内部和友元能访问 double real; //存储复数的实部 double imag; //存储复数的虚部 }; #endif //结束头文件保护宏
#include "Complex.h" // 包含头文件,让编译器知道Complex类的结构 #include <cmath> // 引入数学头文件(因为要计算平方根sqrt,用于取模) //初始化类的静态常量doc const string Complex::doc = "a simplified complex class"; //静态成员必须在“类外”初始化(因为它是“类的属性”,不是对象的属性) //这里给doc赋值为实验要求的说明信息 //普通构造函数的实现 Complex::Complex(double real, double imag) : real(real), imag(imag) {} //Complex:::表示这是Complex类的成员函数 //real(real), imag(imag):初始化列表(高效初始化成员变量) //把形参real的值赋给类的私有成员real //把形参imag的值赋给类的私有成员imag //复制构造函数的实现 Complex::Complex(const Complex& other) : real(other.real), imag(other.imag) {} //other是传入的已有对象 //把other的real和imag的值,赋给新对象的real和imag //作用:保证新对象和原对象的内容完全一致 //get_real()的实现:返回实部 double Complex::get_real() const { return real; // 直接返回私有成员real } //get_imag()的实现:返回虚部 double Complex::get_imag() const { return imag; // 直接返回私有成员imag } //add()的实现:自身累加另一个复数 void Complex::add(const Complex& other) { this->real += other.real; // 当前对象的real = 当前real + other的real this->imag += other.imag; // 当前对象的imag = 当前imag + other的imag //this:指向当前对象的指针(表示“自己”) } //友元函数output()的实现:输出复数(a+bi格式) void output(const Complex& c) { cout << c.real; // 先输出实部 if (c.imag >= 0) { // 如果虚部是正数,输出“+ 虚部i” cout << " + " << c.imag << "i"; } else { // 如果虚部是负数,输出“- 绝对值i”(比如imag=-4 → 输出“- 4i”) cout << " - " << -c.imag << "i"; } } //友元函数abs()的实现:计算复数的模 double abs(const Complex& c) { // 复数的模公式:√(实部2 + 虚部2) return sqrt(c.real * c.real + c.imag * c.imag); } //友元函数add()的实现:两个复数相加,返回新的复数 Complex add(const Complex& c1, const Complex& c2) { // 新复数的实部 = c1实部 + c2实部 // 新复数的虚部 = c1虚部 + c2虚部 return Complex(c1.real + c2.real, c1.imag + c2.imag); } //友元函数is_equal()的实现:判断两个复数是否相等 bool is_equal(const Complex& c1, const Complex& c2) { // 复数相等的条件:实部相等 且 虚部相等 return (c1.real == c2.real) && (c1.imag == c2.imag); } // 11. 友元函数is_not_equal()的实现:判断两个复数是否不相等 bool is_not_equal(const Complex& c1, const Complex& c2) { // 直接复用is_equal的结果,取反即可 return !is_equal(c1, c2); }
#include"Complex.h" #include <iostream> #include <iomanip> #include <complex> void test_Complex(); void test_std_complex(); int main() { std::cout << "*******测试1: 自定义类Complex*******\n"; test_Complex(); std::cout << "\n*******测试2: 标准库模板类complex*******\n"; test_std_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); 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.real = " << c5.get_real() << ", c5.imag = " << c5.get_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; } 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; const std::complex<double> c5(3.5); cout << "c1 = " << c1 << endl; cout << "c2 = " << c2 << endl; cout << "c3 = " << c3 << endl; cout << "c4 = " << c4 << endl; cout << "c5.real = " << c5.real() << ", c5.imag = " << c5.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; }

问题1:
标准库模板类 std::complex 更简洁。有关联
问题2:
①是。因为 output 需要访问复数的实部和虚部来进行输出; abs 需要根据实部和虚部计算复数的模; add 需要访问两个复数的实部和虚部来进行加法运算
②否。标准库std::complex的abs函数并非通过友元实现,而是利用std::complex提供的real()和imag()成员函数来访问实部和虚部,进而计算模长
③外部函数需要直接访问类的私有成员,且该函数与类的逻辑强相关(如复数的输出、运算函数);
实现运算符重载(如非成员的+、<<等运算符),需要访问类的私有数据;
某些设计模式或工具类需要突破封装边界,但又要保证封装的合理性时
问题3:
将拷贝构造函数Complex(const Complex& other);移至private区域,且不在Complex.cpp中实现该函数
实验任务三
#pragma once // 头文件保护(等价于#ifndef...#define...#endif) #include <string> // 枚举类型:表示播放控制指令 enum class ControlType { Play, Pause, Next, Prev, Stop, Unknown }; class PlayerControl { public: // 构造函数 PlayerControl(); // 接口1:将用户输入的字符串(如"play")转换为枚举值 ControlType parse(const std::string& control_str); // 接口2:执行控制指令(模拟播放行为) void execute(ControlType cmd) const; // 类方法:获取操作总次数 static int get_cnt(); private: // 类属性:静态变量,记录所有对象的操作总次数 static int total_cnt; };
#include "PlayerControl.h" #include <iostream> #include <algorithm> // 用于字符串大小写转换 #include <cctype> // 用于字符大小写判断 // 初始化静态成员:操作总次数初始为0 int PlayerControl::total_cnt = 0; // 构造函数:无额外逻辑,仅初始化对象 PlayerControl::PlayerControl() {} // 接口1:字符串转枚举值(忽略大小写) ControlType PlayerControl::parse(const std::string& control_str) { // 步骤1:将输入字符串转为小写(统一处理) std::string lower_str = control_str; std::transform(lower_str.begin(), lower_str.end(), lower_str.begin(), [](unsigned char c) { return std::tolower(c); }); // 步骤2:根据小写字符串匹配枚举值 if (lower_str == "play") { total_cnt++; // 操作次数+1 return ControlType::Play; } else if (lower_str == "pause") { total_cnt++; return ControlType::Pause; } else if (lower_str == "next") { total_cnt++; return ControlType::Next; } else if (lower_str == "prev") { total_cnt++; return ControlType::Prev; } else if (lower_str == "stop") { total_cnt++; return ControlType::Stop; } else { // 未知指令 return ControlType::Unknown; } } // 接口2:执行控制指令(模拟输出) void PlayerControl::execute(ControlType cmd) const { // 根据枚举值输出对应的控制行为 switch (cmd) { case ControlType::Play: std::cout << "[Play] 播放音乐..." << std::endl; break; case ControlType::Pause: std::cout << "[Pause] 音乐已暂停" << std::endl; break; case ControlType::Next: std::cout << "[Next] 切换到下一首" << std::endl; break; case ControlType::Prev: std::cout << "[Prev] 回到上一首" << std::endl; break; case ControlType::Stop: std::cout << "[Stop] 音乐已停止" << std::endl; break; default: std::cout << "[Error] 未知控制指令" << std::endl; break; } } // 类方法:返回操作总次数 int PlayerControl::get_cnt() { return total_cnt; }
#include "PlayerControl.h" #include <iostream> 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") { // 输入quit则退出 break; } // 步骤1:将用户输入的字符串转为枚举指令 ControlType cmd = controller.parse(control_str); // 步骤2:执行指令 controller.execute(cmd); // 步骤3:输出当前操作总次数 std::cout << "Current Player control: " << PlayerControl::get_cnt() << "\n\n"; } } int main() { test(); // 运行测试 return 0; }

实验任务四
#pragma once // 头文件保护:防止同一文件被重复包含(等价于#ifndef+#define+#endif) #include <string> // 引入string类型的头文件(因为要定义类属性doc) using namespace std; // 使用std命名空间,简化代码(避免写std::string) class Fraction { // 定义分数类Fraction public: // 类属性:公有静态常量,用于类说明 static const string doc; // static表示“类的属性”(所有对象共享),const表示不可修改 // 构造函数声明 Fraction(int up = 0, int down = 1); // 普通构造:默认分子0、分母1(支持无参/单参/双参构造) Fraction(const Fraction& other); // 复制构造:用已有对象构造新对象 // 接口方法声明(类的功能函数) int get_up() const; // 返回分子,const表示函数不修改对象成员 int get_down() const; // 返回分母,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); // 分数相除 private: // 私有成员:仅类内部和友元能访问 int up; // 存储分数的分子 int down; // 存储分数的分母 void reduce(); // 内部工具函数:分数化简(约分) int gcd(int a, int b) const; // 内部工具函数:求最大公约数(用于约分) };
#include "Fraction.h" // 包含头文件,让编译器知道Fraction类的结构 #include <iostream> // 引入输入输出头文件(用于输出错误信息) #include <cstdlib> // 引入stdlib头文件(用于abs()函数,求绝对值) // 初始化类的静态常量doc(静态成员必须在类外初始化) const string Fraction::doc = "Fraction类v0.01版.\n目前仅支持分数对象的构造、输出、加减乘除运算"; // 普通构造函数:初始化分子、分母,并处理异常、化简分数 Fraction::Fraction(int up, int down) : up(up), down(down) { // 处理分母为0的错误:直接终止程序并提示 if (down == 0) { cerr << "错误:分母不能为0!" << endl; // cerr:输出错误信息 exit(1); // 终止程序(返回1表示异常退出) } // 确保分母为正:若分母是负数,将符号转移到分子 if (down < 0) { up = -up; // 分子取反 down = -down; // 分母取反(转为正数) } reduce(); // 调用内部工具函数,化简分数(约分) } // 复制构造函数:用已有对象other构造新对象 Fraction::Fraction(const Fraction& other) : up(other.up), down(other.down) {} //other是已有对象的“只读引用” //用other的up和down初始化新对象的up和down // 返回分子(接口方法) int Fraction::get_up() const { return up; // 直接返回私有成员up } // 返回分母(接口方法) int Fraction::get_down() const { return down; // 直接返回私有成员down } // 求负:返回新的分数对象(原对象不变) Fraction Fraction::negative() const { return Fraction(-up, down); // 构造新分数,分子取反、分母不变 } // 内部工具函数:求a和b的最大公约数(用于约分) int Fraction::gcd(int a, int b) const { a = abs(a); // 转为绝对值(避免负数影响计算) b = abs(b); while (b != 0) { // 辗转相除法求最大公约数 int temp = b; b = a % b; a = temp; } return a; // a是最大公约数 } // 内部工具函数:分数化简(约分) void Fraction::reduce() { int common = gcd(up, down); // 求分子和分母的最大公约数 up /= common; // 分子除以最大公约数 down /= common; // 分母除以最大公约数 } // 友元函数:输出分数(化简后的格式) void output(const Fraction& f) { if (f.down == 1) { // 若分母是1,直接输出分子(如2/1 → 2) cout << f.up; } else { // 否则输出“分子/分母”格式(如-2/3) cout << f.up << "/" << f.down; } } // 友元函数:分数相加 Fraction add(const Fraction& f1, const Fraction& f2) { // 分数加法公式:f1 + f2 = (f1.up*f2.down + f2.up*f1.down) / (f1.down*f2.down) 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) { // 分数减法公式:f1 - f2 = (f1.up*f2.down - f2.up*f1.down) / (f1.down*f2.down) 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) { // 分数乘法公式:f1 * f2 = (f1.up*f2.up) / (f1.down*f2.down) 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) { // 分数除法公式:f1 / f2 = (f1.up*f2.down) / (f1.down*f2.up)(等价于乘以f2的倒数) int new_up = f1.up * f2.down; int new_down = f1.down * f2.up; return Fraction(new_up, new_down); }
#include "Fraction.h" // 包含Fraction类的头文件 #include <iostream> // 引入输入输出头文件 void test1(); // 声明测试函数1(基础功能测试) void test2(); // 声明测试函数2(分母为0测试) int main() { // 程序入口 std::cout << "测试1:Fraction类基础功能测试\n"; // 输出测试标题 test1(); // 调用测试函数1 std::cout << "\n测试2:分母为0测试:\n"; // 输出测试标题 test2(); // 调用测试函数2 } void test1() { // 测试函数1:基础功能 using std::cout; // 简化cout的写法(避免写std::cout) using std::endl; // 简化endl的写法 cout << "Fraction类测试:" << endl; cout << Fraction::doc << endl << endl; // 输出类的说明信息 // 构造分数对象 Fraction f1(5); // 单参构造:分子5,分母默认1 → 5/1 Fraction f2(3, -4), f3(-18, 12); // f2:3/-4→-3/4;f3:-18/12→-3/2 Fraction f4(f3); // 复制构造:f4和f3相同→-3/2 // 输出各个分数 cout << "f1 = "; output(f1); cout << endl; // 输出f1:5 cout << "f2 = "; output(f2); cout << endl; // 输出f2:-3/4 cout << "f3 = "; output(f3); cout << endl; // 输出f3:-3/2 cout << "f4 = "; output(f4); cout << endl; // 输出f4:-3/2 // 测试求负功能 const Fraction f5(f4.negative()); // f4求负→3/2 cout << "f5 = "; output(f5); cout << endl; // 输出f5:3/2 // 测试get_up/get_down cout << "f5.get_up() = " << f5.get_up() << ", f5.get_down() = " << f5.get_down() << endl; // 输出3和2 // 测试分数运算 cout << "f1 + f2 = "; output(add(f1, f2)); cout << endl; // 5 + (-3/4) = 17/4 cout << "f1 - f2 = "; output(sub(f1, f2)); cout << endl; // 5 - (-3/4) = 23/4 cout << "f1 * f2 = "; output(mul(f1, f2)); cout << endl; // 5 * (-3/4) = -15/4 cout << "f1 / f2 = "; output(div(f1, f2)); cout << endl; // 5 / (-3/4) = -20/3 cout << "f4 + f5 = "; output(add(f4, f5)); cout << endl; // (-3/2) + 3/2 = 0 } void test2() { // 测试函数2:分母为0的情况 using std::cout; using std::endl; Fraction f6(42, 55), f7(0, 3); // f7:0/3→0/1 cout << "f6 = "; output(f6); cout << endl; // 输出f6:42/55 cout << "f7 = "; output(f7); cout << endl; // 输出f7:0 cout << "f6 / f7 = "; // f6/f7 → 42/55 ÷ 0 → 分母为0,触发构造函数的错误提示 output(div(f6, f7)); cout << endl; }

浙公网安备 33010602011771号