实验2
实验任务1
#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'; std::cout << "func: T objects'current count: " << T::get_cnt() << std::endl; }
task1.cpp
#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()不是T类的成员,缺少函数声明,无法通过编译。
T(int x = 0, int y = 0)的功能是直接使用输入的具体数据初始化创建的类对象的数据变量,在没有初始化或使用具体数据初始化时调用。复制构造函数
T(const T &t)的功能是使用类对象来初始化创建的新的类对象,在使用类对象初始化新的类对象或在函数间按值传递对象时调用。移动构造函数
T(T &&t)的功能是将目标类对象的数据直接“移动”至创建的新类对象的数据变量中,在显式使用move()或编译器自动优化时调用,在函数传值时使用可以避免出现意外的对象拷贝,同时对于大型类必须的值传递可以加快速度,能近似达到传递引用的速度。
问题3:不能正常运行。
截图如下:

由于类中静态数据成员初始化只能有且仅有一次,头文件会被多个文件包含后编译,因此要在.cpp文件中初始化,显然不符合只初始化一次的要求,尽管多次初始化结果时一样的。
实验任务2
代码组织:
Complex.h:类T的声明、友元函数声明
Complex.cpp:类T的实现、友元函数实现
task2.cpp:测试模块、main函数
Complex.h
#ifndef MY_COMPLEX_H_ #define MY_COMPLEX_H_ #include <string> class Complex { // 对象属性、方法 private: double real, imag; public: Complex(double r = 0.0, double i = 0.0); // 普通构造函数 Complex(const Complex&); // 复制构造函数 Complex(const Complex&&) noexcept; // 移动构造函数 double get_real() const; // 显示Complex类对象实部 double get_imag() const; // 显示Complex类对象虚部 Complex& operator=(const Complex&); Complex& operator=(const Complex&&) noexcept; // 重载=运算符 void add(const Complex&); // 将一个Complex类对象加到另一个Complex类对象上 // 类属性、方法 public: static const std::string doc; // 用于类说明 // 类Complex友元函数声明 friend void output(const Complex&); // 以a+bi的形式显示Complex类对象的信息 friend double abs(const Complex&); // 对Complex类对象取模 friend Complex add(const Complex&, const Complex&); // 实现两个Complex类对象相加,返回Complex类对象 friend bool is_equal(const Complex&, const Complex&); // 判断两个Complex类对象是否相等 friend bool is_not_equal(const Complex&, const Complex&); // 判断两个Complex类对象是否相等 }; void output(const Complex&); double abs(const Complex&); Complex add(const Complex&, const Complex&); bool is_equal(const Complex&, const Complex&); bool is_not_equal(const Complex&, const Complex&);
#endif
Complex.cpp
#include "Complex.h" #include <iostream> #include <utility> #include <string> #include <cmath> const std::string Complex::doc = "a smplified complex class"; Complex::Complex(double r, double i): real(r), imag(i) { } Complex::Complex(const Complex &c): real(c.real), imag(c.imag) { } Complex::Complex(const Complex &&c) noexcept : real(c.real), imag(c.imag) { } Complex& Complex::operator=(const Complex &c) { if (this != &c) { real = c.real; imag = c.imag; } return *this; } Complex& Complex::operator=(const Complex &&c) noexcept { if (this != &c) { real = c.real; imag = c.imag; } return *this; } double Complex::get_real() const { return real; } double Complex::get_imag() const { return imag; } void Complex::add(const Complex &c) { real += c.real; imag += c.imag; } void output(const Complex &c) { std::cout << c.get_real() << (c.get_imag() < 0 ? " - " : " + ") << std::abs(c.get_imag()) << 'i'; } double abs(const Complex &c) { return std::sqrt(c.get_real() * c.get_real() + c.get_imag() * c.get_imag()); } Complex add(const Complex &c1, const Complex &c2) { Complex c; c.add(c1); c.add(c2); return c; } bool is_equal(const Complex &c1, const Complex &c2) { return((c1.get_real() == c2.get_real()) && (c1.get_imag() == c2.get_imag())); } bool is_not_equal(const Complex &c1, const Complex &c2) { return !is_equal(c1, c2); }
task2.cpp
#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:
标准库提供的写法更加简洁,使得类对象在使用时更加贴合基本数据类型的编码方式.函数和运算本质上几乎是一致的,运算符本身是一个形如operatorXXX()的函数,通过像重载函数一样重载运算符可以实现标准库模板类的写法。
问题2-1:
是。output()需访问real和imag以格式化输出;abs()需通过real和imag计算模(sqrt(real²+imag²));add()需获取两个复数的real和imag才能计算和,因此必须设为友元访问私有数据。
问题2-2:标准库没有把abs()设为友元函数,而是提供了一种具体化abs(const complex<T>& z)来处理复数取模的问题,正如上一小问提到的,abs()完全不需要访问对象的私有数据成员,因此没必要设为友元函数。
问题2-3:友元的核心作用是 “打破类的封装性,允许特定外部函数或类访问私有成员,仅当外部函数或类需要访问当前类的私有成员,且无法通过公有接口间接获取时,才考虑使用friend。
问题3:使用delete关键字显式指出禁用赋值运算符,同时所有返回对象的功能函数都需要提前传入一个空对象来在函数退出时接收函数原本应该返回的对象。
实验任务3
代码组织:
PlayerControl.h:播放控制类PlayerControl声明
PlayerControl.cpp:播放控制类PlayerControl实现
task3.cpp:测试模块 + main
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 <iostream> #include <algorithm> int PlayerControl::total_cnt = 0; PlayerControl::PlayerControl() {} // 待补足 // 1. 将输入字符串转为小写,实现大小写不敏感 // 2. 匹配"play"/"pause"/"next"/"prev"/"stop"并返回对应枚举 // 3. 未匹配的字符串返回ControlType::Unknown // 4. 每次成功调用parse时递增total_cnt ControlType PlayerControl::parse(const std::string& control_str) { std::string trans_result; for (auto &c : control_str) trans_result += std::tolower(c); ++total_cnt; if ("play" == trans_result) return ControlType::Play; else if ("next" == trans_result) return ControlType::Next; else if ("prev" == trans_result) return ControlType::Prev; else if ("stop" == trans_result) return ControlType::Stop; else if ("pause" == trans_result) return ControlType::Pause; else return ControlType::Unknown; } void PlayerControl::execute(ControlType cmd) const { 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 "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") break; ControlType cmd = controller.parse(control_str); controller.execute(cmd); std::cout << "Current Player control: " << PlayerControl::get_cnt() << "\n\n"; } } int main() { test(); }
测试结果截图如下:

实验任务4
代码组织:
Fraction.h:类Fraction声明、其他声明
Fraction.cpp:类Fraction实现、其他实现
task4.cpp:测试代码、main()函数
Fraction.h
#ifndef FRACTION_H_ #define FRACTION_H_ #include <string> namespace frac { // 数学工具函数 int gcd(int, int); //求最大公因数,用于化简分数 int lcm(int, int); //求最小公倍数,用于分数加减 class Fraction { // 对象属性 方法 public: Fraction(int u = 0, int d = 1); // 默认构造函数 Fraction(Fraction&); // 拷贝构造函数 Fraction(Fraction&&) noexcept; // 移动构造函数 int get_up() const; // 返回Fraction对象的分子 int get_down() const; // 返回Fraction对象的分母 Fraction negative() const; // 对Fraction对象取负 private: int up, down; void simplify(); //对分数进行化简 // 类属性 方法 public: static const std::string doc; }; // 工具函数 void output(const Fraction&); //以a/b形式输出一个分数 Fraction add(const Fraction&, const Fraction&); //实现两个分数相加 Fraction sub(const Fraction&, const Fraction&); //实现两个分数相减 Fraction mul(const Fraction&, const Fraction&); //实现两个分数相乘 Fraction div(const Fraction&, const Fraction&); //实现两个分数相除 } #endif
Fraction.cpp
#include "Fraction.h" #include <iostream> #include <cmath> #include <string> namespace frac { int gcd(int a, int b) { if (a * b == 0) return 0; int temp; while (a % b) { temp = a % b; a = b; b = temp; } return b; } int lcm(int a, int b) { if (a * b == 0) return 0; return a * b / gcd(a, b); } const std::string Fraction::doc = "Fraction类 v 0.01版.\n目前仅支持分数对象的构造、输出、加/减/乘/除运算."; Fraction::Fraction(int u, int d): up(u), down(d) { simplify(); } Fraction::Fraction(Fraction &f): up(f.up), down(f.down) { } Fraction::Fraction(Fraction &&f) noexcept: up(f.up), down(f.down) { } int Fraction::get_up() const { return up; } int Fraction::get_down() const { return down; } Fraction Fraction::negative() const { Fraction f; f.up = -up; f.down = down; return f; } void Fraction::simplify() { if (down < 0) { down *= -1; up *= -1; } int com_fac = gcd(std::abs(up), std::abs(down)); if (com_fac != 1 && com_fac != 0) { up /= com_fac; down /= com_fac; } } void output(const Fraction &f) { if (f.get_down() == 0) std::cout << "分母不能为0"; else if (f.get_down() == 1 || f.get_up() == 0) std::cout << f.get_up(); else std::cout << f.get_up() << '/' << f.get_down(); } Fraction add(const Fraction &f1, const Fraction &f2) { int com_den = lcm(f1.get_down(), f2.get_down()); Fraction rf(com_den / f1.get_down() * f1.get_up() + com_den / f2.get_down() * f2.get_up(), com_den); return rf; } Fraction sub(const Fraction &f1, const Fraction &f2) { int com_den = lcm(f1.get_down(), f2.get_down()); Fraction rf(com_den / f1.get_down() * f1.get_up() - com_den / f2.get_down() * f2.get_up(), com_den); return rf; } Fraction mul(const Fraction &f1, const Fraction &f2) { Fraction rf(f1.get_up() * f2.get_up(), f1.get_down() * f2.get_down()); return rf; } Fraction div(const Fraction &f1, const Fraction &f2) { Fraction rf(f1.get_up() * f2.get_down(), f1.get_down() * f2.get_up()); return rf; } }
task4.cpp
#include "Fraction.h" #include <iostream> void test1(); void test2(); int main() { std::cout << "测试1: Fraction类基础功能测试\n"; test1(); std::cout << "\n测试2: 分母为0测试: \n"; test2(); } void test1() { using std::cout; using std::endl; cout << "Fraction类测试: " << endl; cout << frac::Fraction::doc << endl << endl; frac::Fraction f1(5); frac::Fraction f2(3, -4), f3(-18, 12); frac::Fraction f4(f3); cout << "f1 = "; frac::output(f1); cout << endl; cout << "f2 = "; frac::output(f2); cout << endl; cout << "f3 = "; frac::output(f3); cout << endl; cout << "f4 = "; frac::output(f4); cout << endl; const frac::Fraction f5(f4.negative()); cout << "f5 = "; frac::output(f5); cout << endl; cout << "f5.get_up() = " << f5.get_up() << ", f5.get_down() = " << f5.get_down() << endl; cout << "f1 + f2 = "; frac::output(frac::add(f1, f2)); cout << endl; cout << "f1 - f2 = "; frac::output(frac::sub(f1, f2)); cout << endl; cout << "f1 * f2 = "; frac::output(frac::mul(f1, f2)); cout << endl; cout << "f1 / f2 = "; frac::output(frac::div(f1, f2)); cout << endl; cout << "f4 + f5 = "; frac::output(frac::add(f4, f5)); cout << endl; } void test2() { using std::cout; using std::endl; frac::Fraction f6(42, 55), f7(0, 3); cout << "f6 = "; frac::output(f6); cout << endl; cout << "f7 = "; frac::output(f7); cout << endl; cout << "f6 / f7 = "; frac::output(frac::div(f6, f7)); cout << endl; }
测试结果截图如下:

分数的输出和计算, output/add/sub/mul/div ,你选择的是哪一种设计方案?
(友元/自由函数/命名空间+自由函数/类+static)你的决策理由?如友元方案的优缺点、静态成员函数方案的适用场景、命名空间方案的考虑因素等。
在该场景下,我采用“命名空间 + 自由函数”的组合来完成分数的打印与运算。首先,没有任何函数需要直接触碰类的数据成员,因此可以把封装性风险降到最低,也自然避开了友元这把“破窗锤”。其次,无论是加减乘除还是流式输出,这些操作与 Fraction 本身并不存在强耦合——未来极可能为 Rational、Decimal 乃至 Matrix 提供同名重载;若写成静态成员,不仅会在各头文件里滋生大量“隐形耦合”,还会让后续重构变成“牵一发而动全身”的冒险。自由函数则毫无此类包袱:它只关心接口,不关心内存布局,底层字段如何调整都无需改动调用方。最后,所有接口统一收拢在 frac 命名空间内,既杜绝了与 std:: 或用户代码的无意冲突,又给未来版本留出了“渐进式扩展”的余地——新增功能只需往命名空间里再丢一个重载,而无需回炉改写任何已有类定义。
实验总结:
1、静态成员变量要在类内声明,类外初始化,不然可能出现难以解决的bug,但其他的函数没有这个要求,可以直接在.h的头文件中进行初始化,简化代码。
2.类的封装性使得使用者能更加灵活自由的组织代码,由编译器来自动完成底层细节的操作,编译器对于类的处理有很多自动行为,例如构造函数,析构函数的隐式创建和调用,但这些自动行为可能造成最终的程序与目标实现效果不同,因此基于C++信任使用者的理念,允许用户重载这些函数。
3.检查每个函数在所以.cpp文件中只定义了一次,多文件中要小心重定义的问题来尽量减少报错。

浙公网安备 33010602011771号