实验2
一、实验任务1
源代码task1
1 #pragma once 2 3 #include <string> 4 5 // 类T: 声明 6 class T { 7 // 对象属性、方法 8 public: 9 T(int x = 0, int y = 0); // 普通构造函数 10 T(const T &t); // 复制构造函数 11 T(T &&t); // 移动构造函数 12 ~T(); // 析构函数 13 14 void adjust(int ratio); // 按系数成倍调整数据 15 void display() const; // 以(m1, m2)形式显示T类对象信息 16 17 private: 18 int m1, m2; 19 20 // 类属性、方法 21 public: 22 static int get_cnt(); // 显示当前T类对象总数 23 24 public: 25 static const std::string doc; // 类T的描述信息 26 static const int max_cnt; // 类T对象上限 27 28 private: 29 static int cnt; // 当前T类对象数目 30 31 // 类T友元函数声明 32 friend void func(); 33 }; 34 35 // 普通函数声明 36 void func();
1 #include "T.h" 2 #include <iostream> 3 #include <string> 4 5 // 类T实现 6 7 // static成员数据类外初始化 8 const std::string T::doc{"a simple class sample"}; 9 const int T::max_cnt = 999; 10 int T::cnt = 0; 11 12 // 类方法 13 int T::get_cnt() { 14 return cnt; 15 } 16 17 // 对象方法 18 T::T(int x, int y): m1{x}, m2{y} { 19 ++cnt; 20 std::cout << "T constructor called.\n"; 21 } 22 23 T::T(const T &t): m1{t.m1}, m2{t.m2} { 24 ++cnt; 25 std::cout << "T copy constructor called.\n"; 26 } 27 28 T::T(T &&t): m1{t.m1}, m2{t.m2} { 29 ++cnt; 30 std::cout << "T move constructor called.\n"; 31 } 32 33 T::~T() { 34 --cnt; 35 std::cout << "T destructor called.\n"; 36 } 37 38 void T::adjust(int ratio) { 39 m1 *= ratio; 40 m2 *= ratio; 41 } 42 43 void T::display() const { 44 std::cout << "(" << m1 << ", " << m2 << ")" ; 45 } 46 47 // 普通函数实现 48 void func() { 49 T t5(42); 50 t5.m2 = 2049; 51 std::cout << "t5 = "; t5.display(); std::cout << '\n'; 52 }
1 #include "T.h" 2 #include <iostream> 3 4 void test_T(); 5 6 int main() { 7 std::cout << "test Class T: \n"; 8 test_T(); 9 10 std::cout << "\ntest friend func: \n"; 11 func(); 12 } 13 14 void test_T() { 15 using std::cout; 16 using std::endl; 17 18 cout << "T info: " << T::doc << endl; 19 cout << "T objects'max count: " << T::max_cnt << endl; 20 cout << "T objects'current count: " << T::get_cnt() << endl << endl; 21 22 T t1; 23 cout << "t1 = "; t1.display(); cout << endl; 24 25 T t2(3, 4); 26 cout << "t2 = "; t2.display(); cout << endl; 27 28 T t3(t2); 29 t3.adjust(2); 30 cout << "t3 = "; t3.display(); cout << endl; 31 32 T t4(std::move(t2)); 33 cout << "t4 = "; t4.display(); cout << endl; 34 35 cout << "test: T objects'current count: " << T::get_cnt() << endl; 36 }
运行结果截图

问题1:T.h中,在类T内部,已声明 func 是T的友元函数。在类外部,去掉line36,重新编译,程序能否正常运行?如果能,回答YES;如果不能,以截图形式提供编译报错信息,说明原因。

不能。友元函数func需要在类外声明才可以在类外使用。
问题2:T.h中,line9-12给出了各种构造函数、析构函数。总结它们各自的功能、调用时机。
默认构造函数 功能:无参调用。未定义其他构造函数时编译器自动生成空实现;反之不生成。 调用时机:无参创建对象时。
普通构造函数 功能:用给定参数初始化对象。 调用时机:带参数创建对象时。
复制构造函数 功能:用同类对象初始化新对象。 调用时机:用同类对象初始化新对象时。
移动构造函数 功能:用同类右值对象初始化新对象。 调用时机:用右值引用初始化新对象时。
析构函数 功能:释放内存及清理资源。 调用时机:对象生存期结束时自动调用。
问题3:T.cpp中,line13-15,剪切到T.h的末尾,重新编译,程序能否正确编译。如不能,以截图形式给出报错信息,分析原因。

不能。静态成员变量出现了多重定义,导致出错。
二、实验任务2
源代码task2
1 #pragma once 2 #include <iostream> 3 #include <string> 4 5 class Complex { 6 public: 7 static constexpr const char* doc = "A Simplified Complex Class"; 8 9 Complex(): real_(0.0), imag_(0.0) {}; 10 Complex(double real, double imag = 0.0): real_(real), imag_(imag) {}; 11 Complex(const Complex& other) = default; 12 13 double get_real() const; 14 double get_imag() const; 15 16 void add(const Complex& other); 17 friend bool is_equal(const Complex& c1 , const Complex& c2); 18 friend bool is_not_equal(const Complex& c1 , const Complex& c2); 19 friend Complex add(const Complex& c1, const Complex& c2); 20 friend double abs(const Complex& c); 21 friend void output(const Complex& c); 22 23 private: 24 double real_; 25 double imag_; 26 };
1 #include "Complex.h" 2 #include <cmath> 3 #include <string> 4 #include <iostream> 5 #include <iomanip> 6 7 double Complex::get_real() const { 8 return real_; 9 } 10 11 double Complex::get_imag() const { 12 return imag_; 13 } 14 15 void Complex::add(const Complex& other) { 16 real_ += other.real_; 17 imag_ += other.imag_; 18 } 19 20 bool is_equal(const Complex& c1, const Complex& c2) { 21 return (c1.real_ == c2.real_) && (c1.imag_ == c2.imag_); 22 } 23 24 bool is_not_equal(const Complex& c1, const Complex& c2) { 25 return !is_equal(c1, c2); 26 } 27 28 Complex add(const Complex& c1, const Complex& c2){ 29 return Complex(c1.real_ + c2.real_, c1.imag_ + c2.imag_); 30 } 31 32 double abs(const Complex& c) { 33 return std::sqrt(c.real_ * c.real_ + c.imag_ * c.imag_); 34 } 35 36 void output(const Complex& c){ 37 if (c.imag_ >= 0) 38 { 39 std::cout << std::setw(2) << c.real_ << " + " << c.imag_ << "i"; 40 } 41 else 42 { 43 std::cout << std::setw(2) << c.real_ << " - " << -c.imag_ << "i"; 44 } 45 }
1 #include "Complex.h" 2 #include <iostream> 3 #include <iomanip> 4 #include <complex> 5 6 void test_Complex(); 7 void test_std_complex(); 8 9 int main() { 10 std::cout << "*******测试1: 自定义类Complex*******\n"; 11 test_Complex(); 12 13 std::cout << "\n*******测试2: 标准库模板类complex*******\n"; 14 test_std_complex(); 15 16 system("pause"); 17 } 18 19 void test_Complex() { 20 using std::cout; 21 using std::endl; 22 using std::boolalpha; 23 24 cout << "类成员测试: " << endl; 25 cout << Complex::doc << endl << endl; 26 27 cout << "Complex对象测试: " << endl; 28 Complex c1; 29 Complex c2(3, -4); 30 Complex c3(c2); 31 Complex c4 = c2; 32 const Complex c5(3.5); 33 34 cout << "c1 = "; output(c1); cout << endl; 35 cout << "c2 = "; output(c2); cout << endl; 36 cout << "c3 = "; output(c3); cout << endl; 37 cout << "c4 = "; output(c4); cout << endl; 38 cout << "c5.real = " << c5.get_real() 39 << ", c5.imag = " << c5.get_imag() << endl << endl; 40 41 cout << "复数运算测试: " << endl; 42 cout << "abs(c2) = " << abs(c2) << endl; 43 c1.add(c2); 44 cout << "c1 += c2, c1 = "; output(c1); cout << endl; 45 cout << boolalpha; 46 cout << "c1 == c2 : " << is_equal(c1, c2) << endl; 47 cout << "c1 != c2 : " << is_not_equal(c1, c2) << endl; 48 c4 = add(c2, c3); 49 cout << "c4 = c2 + c3, c4 = "; output(c4); cout << endl; 50 } 51 52 void test_std_complex() { 53 using std::cout; 54 using std::endl; 55 using std::boolalpha; 56 57 cout << "std::complex<double>对象测试: " << endl; 58 std::complex<double> c1; 59 std::complex<double> c2(3, -4); 60 std::complex<double> c3(c2); 61 std::complex<double> c4 = c2; 62 const std::complex<double> c5(3.5); 63 64 cout << "c1 = " << c1 << endl; 65 cout << "c2 = " << c2 << endl; 66 cout << "c3 = " << c3 << endl; 67 cout << "c4 = " << c4 << endl; 68 69 cout << "c5.real = " << c5.real() 70 << ", c5.imag = " << c5.imag() << endl << endl; 71 72 cout << "复数运算测试: " << endl; 73 cout << "abs(c2) = " << abs(c2) << endl; 74 c1 += c2; 75 cout << "c1 += c2, c1 = " << c1 << endl; 76 cout << boolalpha; 77 cout << "c1 == c2 : " << (c1 == c2)<< endl; 78 cout << "c1 != c2 : " << (c1 != c2) << endl; 79 c4 = c2 + c3; 80 cout << "c4 = c2 + c3, c4 = " << c4 << endl; 81 }
运行结果截图

问题1:比较自定义类Complex和标准库模板类complex的用法,在使用形式上,哪一种更简洁?函数和运算内在有关联吗?
标准库模板类 complex 更简洁; 函数和运算函数和运算在本质上是等效的。
问题2-1:自定义 Complex 中,output/abs/add/ 等均设为友元,它们真的需要访问私有数据吗?(回答"是/否"并给出理由)
否;原因是在自定义 Complex 中,output、abs、add 等函数的参数均为 Complex 类的对象,若要使用该对象的私有数据,可借助其成员函数 get_real () 和 get_imag () 来获取,无需直接访问私有数据,直接访问反而会破坏类的封装性与隐藏性。
问题2-2:标准库 std::complex 是否把 abs 设为友元?
标准库 std::complex 没有将 abs 设为友元。
问题2-3:什么时候才考虑使用 friend ? 总结你的思考。
在以下情况可考虑使用 friend:一是使用公有接口会带来较大性能损耗时;二是运算符需要对左右操作数拥有对称的访问权限时。
问题3:如果构造对象时禁用 = 形式,即遇到 Complex c4 = c2; 编译报错,类 Complex 的设计应如何调整?
若要禁止以 “=” 形式构造对象(如 Complex c4 = c2; 编译报错),可对类 Complex 进行如下调整:禁用复制构造函数的隐式拷贝,采用显式拷贝的复制构造函数,例如通过 Complex c4 (c2); 的方式来构造对象。
三、实验任务3
源代码task3
1 #include "PlayerControl.h" 2 #include <algorithm> 3 #include <string> 4 5 int PlayerControl::total_cnt = 0; 6 7 PlayerControl::PlayerControl() {} 8 9 ControlType PlayerControl::parse(const std::string& control_str) { 10 // 转小写处理 11 std::string lower_str = control_str; 12 for (char& c : lower_str) { 13 c = tolower(c); 14 } 15 16 // 匹配命令 17 if (lower_str == "play") { 18 total_cnt++; 19 return ControlType::Play; 20 } else if (lower_str == "pause") { 21 total_cnt++; 22 return ControlType::Pause; 23 } else if (lower_str == "next") { 24 total_cnt++; 25 return ControlType::Next; 26 } else if (lower_str == "prev") { 27 total_cnt++; 28 return ControlType::Prev; 29 } else if (lower_str == "stop") { 30 total_cnt++; 31 return ControlType::Stop; 32 } else { 33 return ControlType::Unknown; 34 } 35 } 36 37 void PlayerControl::execute(ControlType cmd) const { 38 switch (cmd) { 39 case ControlType::Play: 40 std::cout << "[play] Playing music...\n"; 41 break; 42 case ControlType::Pause: 43 std::cout << "[Pause] Music paused\n"; 44 break; 45 case ControlType::Next: 46 std::cout << "[Next] Skipping to next track\n"; 47 break; 48 case ControlType::Prev: 49 std::cout << "[Prev] Back to previous track\n"; 50 break; 51 case ControlType::Stop: 52 std::cout << "[Stop] Music stopped\n"; 53 break; 54 default: 55 std::cout << "[Error] unknown control\n"; 56 break; 57 } 58 } 59 60 int PlayerControl::get_cnt() { 61 return total_cnt; 62 }
1 #pragma once 2 #include <string> 3 4 enum class ControlType {Play, Pause, Next, Prev, Stop, Unknown}; 5 6 class PlayerControl { 7 public: 8 PlayerControl(); 9 10 ControlType parse(const std::string& control_str); // 实现std::string --> ControlType转换 11 void execute(ControlType cmd) const; // 执行控制操作(以打印输出模拟) 12 13 static int get_cnt(); 14 15 private: 16 static int total_cnt; 17 };
1 #include "PlayerControl.h" 2 #include <iostream> 3 4 void test() { 5 PlayerControl controller; 6 std::string control_str; 7 std::cout << "Enter Control: (play/pause/next/prev/stop/quit):\n"; 8 9 while(std::cin >> control_str) { 10 if(control_str == "quit") 11 break; 12 13 ControlType cmd = controller.parse(control_str); 14 controller.execute(cmd); 15 std::cout << "Current Player control: " << PlayerControl::get_cnt() << "\n\n"; 16 } 17 } 18 19 int main() { 20 test(); 21 }
选做:控制台输出emoji:添加UTF-8编码代码
运行结果截图

四、实验任务4
源代码task4
1 #ifndef FRACTION_H 2 #define FRACTION_H 3 4 #include <string> 5 6 class Fraction { 7 public: 8 static const std::string doc; 9 10 Fraction(int up = 0); 11 Fraction(int up, int down); 12 Fraction(const Fraction& other); 13 14 int get_up() const; 15 int get_down() const; 16 Fraction negative() const; 17 18 friend void output(const Fraction& f); 19 friend Fraction add(const Fraction& f1, const Fraction& f2); 20 friend Fraction sub(const Fraction& f1, const Fraction& f2); 21 friend Fraction mul(const Fraction& f1, const Fraction& f2); 22 friend Fraction div(const Fraction& f1, const Fraction& f2); 23 24 private: 25 int up; 26 int down; 27 void simplify(); 28 int gcd(int a, int b); 29 }; 30 31 #endif
1 #include "Fraction.h" 2 #include <iostream> 3 #include <cmath> 4 5 const std::string Fraction::doc = "Fraction类 v0.01版. 支持分数的基本运算."; 6 7 Fraction::Fraction(int up) : up(up), down(1) { 8 simplify(); 9 } 10 11 Fraction::Fraction(int up, int down) : up(up), down(down) { 12 if (down == 0) { 13 std::cout << "分母不能为0,已设为1" << std::endl; 14 this->down = 1; 15 } 16 simplify(); 17 } 18 19 Fraction::Fraction(const Fraction& other) : up(other.up), down(other.down) {} 20 21 int Fraction::get_up() const { return up; } 22 int Fraction::get_down() const { return down; } 23 24 Fraction Fraction::negative() const { 25 return Fraction(-up, down); 26 } 27 28 int Fraction::gcd(int a, int b) { 29 a = abs(a); 30 b = abs(b); 31 while (b != 0) { 32 int temp = a % b; 33 a = b; 34 b = temp; 35 } 36 return a; 37 } 38 39 void Fraction::simplify() { 40 if (down < 0) { 41 up = -up; 42 down = -down; 43 } 44 int common = gcd(up, down); 45 if (common != 0) { 46 up /= common; 47 down /= common; 48 } 49 } 50 51 void output(const Fraction& f) { 52 if (f.down == 1) { 53 std::cout << f.up; 54 } else { 55 std::cout << f.up << "/" << f.down; 56 } 57 } 58 59 Fraction add(const Fraction& f1, const Fraction& f2) { 60 int new_up = f1.up * f2.down + f2.up * f1.down; 61 int new_down = f1.down * f2.down; 62 return Fraction(new_up, new_down); 63 } 64 65 Fraction sub(const Fraction& f1, const Fraction& f2) { 66 int new_up = f1.up * f2.down - f2.up * f1.down; 67 int new_down = f1.down * f2.down; 68 return Fraction(new_up, new_down); 69 } 70 71 Fraction mul(const Fraction& f1, const Fraction& f2) { 72 int new_up = f1.up * f2.up; 73 int new_down = f1.down * f2.down; 74 return Fraction(new_up, new_down); 75 } 76 77 Fraction div(const Fraction& f1, const Fraction& f2) { 78 if (f2.up == 0) { 79 std::cout << "分母不能为"; 80 return Fraction(0, 1); 81 } 82 int new_up = f1.up * f2.down; 83 int new_down = f1.down * f2.up; 84 return Fraction(new_up, new_down); 85 }
1 #include "Fraction.h" 2 #include <iostream> 3 4 void test1(); 5 void test2(); 6 7 int main() { 8 std::cout << "测试1: Fraction类基础功能测试\n"; 9 test1(); 10 11 std::cout << "\n测试2: 分母为0测试: \n"; 12 test2(); 13 } 14 15 void test1() { 16 using std::cout; 17 using std::endl; 18 19 cout << "Fraction类测试: " << endl; 20 cout << Fraction::doc << endl << endl; 21 22 Fraction f1(5); 23 Fraction f2(3, -4), f3(-18, 12); 24 Fraction f4(f3); 25 cout << "f1 = "; output(f1); cout << endl; 26 cout << "f2 = "; output(f2); cout << endl; 27 cout << "f3 = "; output(f3); cout << endl; 28 cout << "f4 = "; output(f4); cout << endl; 29 30 const Fraction f5(f4.negative()); 31 cout << "f5 = "; output(f5); cout << endl; 32 cout << "f5.get_up() = " << f5.get_up() 33 << ", f5.get_down() = " << f5.get_down() << endl; 34 35 cout << "f1 + f2 = "; output(add(f1, f2)); cout << endl; 36 cout << "f1 - f2 = "; output(sub(f1, f2)); cout << endl; 37 cout << "f1 * f2 = "; output(mul(f1, f2)); cout << endl; 38 cout << "f1 / f2 = "; output(div(f1, f2)); cout << endl; 39 cout << "f4 + f5 = "; output(add(f4, f5)); cout << endl; 40 } 41 42 void test2() { 43 using std::cout; 44 using std::endl; 45 46 Fraction f6(42, 55), f7(0, 3); 47 cout << "f6 = "; output(f6); cout << endl; 48 cout << "f7 = "; output(f7); cout << endl; 49 cout << "f6 / f7 = "; output(div(f6, f7)); cout << endl; 50 }
运行结果截图

问题:分数的输出和计算,output/add/sub/mul/div,你选择的是哪一种设计方案?(友元/自由函数/命名空间+自由函数/类+static)你的决策理由?如友元方案的优缺点、静态成员函数方案的适用场景、命名空间方案的考虑因素等。
选择的是 命名空间 + 自由函数
做出这一选择的原因是:采用友元方案会对类的封装性和隐藏性造成破坏;静态成员函数方案会导致类内部包含过多函数方法,不利于后续的扩展与维护;而命名空间方案不仅扩展性和维护性较好,还更便于团队协作。
实验总结:
对于项目的创建、编译以及运行流程,我的操作更加熟练了。
浙公网安备 33010602011771号