实验2
实验任务1:
源代码:
main.cpp:
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 }
T.h:
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();
T.cpp:
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:T.h中,在类T内部,已声明 func 是T的友元函数。在类外部,去掉line36,重新编译,程序能否正常运行。如果能,回答YES;如果不能,以截图形式提供编译报错信息,说明原因。
答:
友元函数必须在被调用的作用域中提前声明,而去掉line36后,未在作用域中声明func()函数。
问题2:T.h中,line9-12给出了各种构造函数、析构函数。总结它们各自的功能、调用时机。
答:T(int x = 0, int y = 0)为普通构造函数,用于对象的初始化,首次构造时调用;
T(const T &t)为 复制构造函数,是用已有的对象来初始化新对象,拷贝时调用;
T(T &&t)为移动构造函数,用右值来初始化新对象,实现资源的转移,将已有对象的资源转移给新对象时调用;
~T()为析构函数,用于资源的释放,对象生命周期结束时自动调用。
问题3:T.cpp中,line13-15,剪切到T.h的末尾,重新编译,程序能否正确编译。如不能,以截图形式给出报错信息,分析原因。
答:
移动后显示重复定义。T.h是类的声明头文件,而函数的实现应该放到T.cpp中,否则在这里会被定义两次,因为每个包含T.h的.cpp文件都会编译一遍。
实验任务2:
源代码:
main.cpp:
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 { 11 std::cout << "*******测试1: 自定义类Complex*******\n"; 12 test_Complex(); 13 14 std::cout << "\n*******测试2: 标准库模板类complex*******\n"; 15 test_std_complex(); 16 } 17 18 void test_Complex() 19 { 20 using std::boolalpha; 21 using std::cout; 22 using std::endl; 23 24 cout << "类成员测试: " << endl; 25 cout << Complex::doc << endl 26 << endl; 27 28 cout << "Complex对象测试: " << endl; 29 Complex c1; 30 Complex c2(3, -4); 31 Complex c3(c2); 32 Complex c4 = c2; 33 const Complex c5(3.5); 34 35 cout << "c1 = "; 36 output(c1); 37 cout << endl; 38 cout << "c2 = "; 39 output(c2); 40 cout << endl; 41 cout << "c3 = "; 42 output(c3); 43 cout << endl; 44 cout << "c4 = "; 45 output(c4); 46 cout << endl; 47 cout << "c5.real = " << c5.get_real() 48 << ", c5.imag = " << c5.get_imag() << endl 49 << endl; 50 51 cout << "复数运算测试: " << endl; 52 cout << "abs(c2) = " << abs(c2) << endl; 53 c1.add(c2); 54 cout << "c1 += c2, c1 = "; 55 output(c1); 56 cout << endl; 57 cout << boolalpha; 58 cout << "c1 == c2 : " << is_equal(c1, c2) << endl; 59 cout << "c1 != c2 : " << is_not_equal(c1, c2) << endl; 60 c4 = add(c2, c3); 61 cout << "c4 = c2 + c3, c4 = "; 62 output(c4); 63 cout << endl; 64 } 65 66 void test_std_complex() 67 { 68 using std::boolalpha; 69 using std::cout; 70 using std::endl; 71 72 cout << "std::complex<double>对象测试: " << endl; 73 std::complex<double> c1; 74 std::complex<double> c2(3, -4); 75 std::complex<double> c3(c2); 76 std::complex<double> c4 = c2; 77 const std::complex<double> c5(3.5); 78 79 cout << "c1 = " << c1 << endl; 80 cout << "c2 = " << c2 << endl; 81 cout << "c3 = " << c3 << endl; 82 cout << "c4 = " << c4 << endl; 83 84 cout << "c5.real = " << c5.real() 85 << ", c5.imag = " << c5.imag() << endl 86 << endl; 87 88 cout << "复数运算测试: " << endl; 89 cout << "abs(c2) = " << abs(c2) << endl; 90 c1 += c2; 91 cout << "c1 += c2, c1 = " << c1 << endl; 92 cout << boolalpha; 93 cout << "c1 == c2 : " << (c1 == c2) << endl; 94 cout << "c1 != c2 : " << (c1 != c2) << endl; 95 c4 = c2 + c3; 96 cout << "c4 = c2 + c3, c4 = " << c4 << endl; 97 }
Complex.h:
1 #pragma once 2 #include <string> 3 4 class Complex{ 5 public: 6 static const std::string doc; 7 8 Complex (); 9 Complex (double r); 10 Complex (double r, double i); 11 Complex (const Complex& z); 12 private: 13 double real; 14 double imag; 15 public: 16 double get_real() const; 17 double get_imag() const; 18 void add(const Complex& z); 19 20 friend void output(const Complex& z); 21 friend double abs(const Complex& z); 22 friend Complex add(const Complex& z1, const Complex& z2); 23 friend bool is_equal(const Complex& z1, const Complex& z2); 24 friend bool is_not_equal(const Complex& z1, const Complex& z2); 25 };
Complex.cpp:
#include "Complex.h" #include <iostream> #include <cmath> const std::string Complex::doc{"a simplified Complex class"}; Complex::Complex () :real(0.0), imag(0.0) {}; Complex::Complex (double r) :real(r), imag(0.0) {}; Complex::Complex (double r1, double r2) :real(r1), imag(r2) {}; Complex::Complex (const Complex &c) :real(c.real), imag(c.imag) {}; double Complex::get_real () const {return real;} double Complex::get_imag () const {return imag;} void Complex::add(const Complex& z) { real = real + z.real; imag = imag + z.imag; } void output(const Complex& z) { std::cout << z.real << (z.imag >= 0?"+":"-" )<< std::abs(z.imag) << "i"; } double abs(const Complex& z) { return sqrt(z.real*z.real + z.imag*z.imag); } Complex add(const Complex& z1, const Complex& z2) { Complex z; z.real = z1.real + z2.real; z.imag = z1.imag + z2.imag; return z; } bool is_equal(const Complex& z1, const Complex& z2) { return z1.real == z2.real && z1.imag == z2.imag; } bool is_not_equal (const Complex& z1, const Complex& z2) { return z1.real != z2.real || z1.imag != z2.imag; }
问题1:比较自定义类 Complex 和标准库模板类 complex 的用法,在使用形式上,哪一种更简洁?函数和运算内在有关联吗?
答:标准库模板类 complex更简洁。有,二者都可以实现复数的操作和运算,但是标准库模板类 complex 已经重载运算符,用起来更简单。
问题2:
2-1:自定义 Complex 中, output/abs/add/ 等均设为友元,它们真的需要访问 私有数据 吗?(回答“是/否”并给出理由)
答:是,需要访问私有成员real和imag。
2-2:标准库 std::complex 是否把 abs 设为友元?(查阅 cppreference后回答)
答:否。std::abs只是普通的函数模板。
2-3:什么时候才考虑使用 friend?总结你的思考。
答:需要访问私有成员且无法通过公有接口高效完成时。
问题3:如果构造对象时禁用=形式,即遇到 Complex c4 = c2; 编译报错,类Complex的设计应如何调整?
答:把拷贝构造函数声明为explicit。
实验任务3:
源代码:
main.cpp:
1 #include "PlayerControl.h" 2 #include <iostream> 3 4 void test() 5 { 6 PlayerControl controller; 7 std::string control_str; 8 std::cout << "Enter Control: (play/pause/next/prev/stop/quit):\n"; 9 10 while (std::cin >> control_str) 11 { 12 if (control_str == "quit") 13 break; 14 15 ControlType cmd = controller.parse(control_str); 16 controller.execute(cmd); 17 std::cout << "Current Player control: " << PlayerControl::get_cnt() << "\n\n"; 18 } 19 } 20 21 int main() 22 { 23 test(); 24 }
PlayerControl.h:
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); 11 void execute(ControlType cmd) const; 12 13 static int get_cnt(); 14 15 private: 16 static int total_cnt; 17 };
PlayerControl.cpp:
1 #include "PlayerControl.h" 2 #include <iostream> 3 #include <algorithm> 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 cmd = control_str; 12 std::transform(cmd.begin(),cmd.end(),cmd.begin(),[](auto c){return towlower(c);}); 13 total_cnt++; 14 15 if (cmd == "play") 16 return ControlType::Play; 17 if (cmd == "pause") 18 return ControlType::Pause; 19 if (cmd == "next") 20 return ControlType::Next; 21 if (cmd == "prev") 22 return ControlType::Prev; 23 if (cmd == "stop") 24 return ControlType::Stop; 25 return ControlType::Unknown; 26 } 27 28 void PlayerControl::execute(ControlType cmd) const 29 { 30 switch (cmd) 31 { 32 case ControlType::Play: 33 std::cout << "[play] Playing music...\n"; 34 break; 35 case ControlType::Pause: 36 std::cout << "[Pause] Music paused\n"; 37 break; 38 case ControlType::Next: 39 std::cout << "[Next] Skipping to next track\n"; 40 break; 41 case ControlType::Prev: 42 std::cout << "[Prev] Back to previous track\n"; 43 break; 44 case ControlType::Stop: 45 std::cout << "[Stop] Music stopped\n"; 46 break; 47 default: 48 std::cout << "[Error] unknown control\n"; 49 break; 50 } 51 } 52 53 int PlayerControl::get_cnt() 54 { 55 return total_cnt; 56 }
运行结果:

试验任务4:
源代码:
main.cpp:
1 #include "Fraction.h" 2 #include <iostream> 3 4 void test1(); 5 void test2(); 6 7 int main() 8 { 9 std::cout << "测试1: Fraction类基础功能测试\n"; 10 test1(); 11 12 std::cout << "\n测试2: 分母为0测试: \n"; 13 test2(); 14 } 15 16 void test1() 17 { 18 using std::cout; 19 using std::endl; 20 21 cout << "Fraction类测试: " << endl; 22 cout << Fraction::doc << endl 23 << endl; 24 25 Fraction f1(5); 26 Fraction f2(3, -4), f3(-18, 12); 27 Fraction f4(f3); 28 cout << "f1 = "; 29 output(f1); 30 cout << endl; 31 cout << "f2 = "; 32 output(f2); 33 cout << endl; 34 cout << "f3 = "; 35 output(f3); 36 cout << endl; 37 cout << "f4 = "; 38 output(f4); 39 cout << endl; 40 41 const Fraction f5(f4.negative()); 42 cout << "f5 = "; 43 output(f5); 44 cout << endl; 45 cout << "f5.get_up() = " << f5.get_up() 46 << ", f5.get_down() = " << f5.get_down() << endl; 47 48 cout << "f1 + f2 = "; 49 output(add(f1, f2)); 50 cout << endl; 51 cout << "f1 - f2 = "; 52 output(sub(f1, f2)); 53 cout << endl; 54 cout << "f1 * f2 = "; 55 output(mul(f1, f2)); 56 cout << endl; 57 cout << "f1 / f2 = "; 58 output(div(f1, f2)); 59 cout << endl; 60 cout << "f4 + f5 = "; 61 output(add(f4, f5)); 62 cout << endl; 63 } 64 65 void test2() 66 { 67 using std::cout; 68 using std::endl; 69 70 Fraction f6(42, 55), f7(0, 3); 71 cout << "f6 = "; 72 output(f6); 73 cout << endl; 74 cout << "f7 = "; 75 output(f7); 76 cout << endl; 77 cout << "f6 / f7 = "; 78 output(div(f6, f7)); 79 cout << endl; 80 }
Fraction.h:
1 #pragma once 2 #include<string> 3 4 class Fraction{ 5 public: 6 static const std::string doc; 7 8 Fraction(int u); 9 Fraction(int u,int d); 10 Fraction(const Fraction&s); 11 12 int get_up()const; 13 int get_down()const; 14 Fraction negative()const; 15 16 friend void output(const Fraction &s); 17 friend Fraction add(const Fraction &s1,const Fraction &s2); 18 friend Fraction sub(const Fraction &s1, const Fraction &s2); 19 friend Fraction mul(const Fraction &s1, const Fraction &s2); 20 friend Fraction div(const Fraction &s1, const Fraction &s2); 21 22 private : 23 int up,down; 24 };
Fraction.cpp:
1 #include "Fraction.h" 2 #include<iostream> 3 #include<cstdlib> 4 5 inline int gcd(int a, int b) 6 { 7 a = std::abs(a); 8 b = std::abs(b); 9 while (b != 0) 10 { 11 int t = b; 12 b = a % b; 13 a = t; 14 } 15 return a; 16 } 17 18 const std::string Fraction::doc{"Fraction类 v 0.01版. 目前仅支持分数对象的构造、输出、加/减/乘/除运算."}; 19 20 Fraction::Fraction(int u) : up{u}, down{1} {}; 21 Fraction::Fraction(int u,int d) : up{u}, down{d} { 22 if(down<0){ 23 up=-up; 24 down=-down; 25 } 26 int a = gcd(up,down); 27 up = up / a; 28 down = down / a; 29 }; 30 Fraction::Fraction(const Fraction &s):up{s.up},down{s.down}{} 31 32 int Fraction::get_up() const 33 { 34 return up; 35 } 36 37 int Fraction::get_down()const 38 { 39 return down; 40 } 41 Fraction Fraction::negative()const 42 { 43 return Fraction(-up,down); 44 } 45 46 void output(const Fraction &s){ 47 if(s.down == 0) 48 std::cout << "分母不能为0"; 49 else if(s.down == 1) 50 std::cout<<s.up; 51 else 52 std::cout<<s.up<<"/"<<s.down; 53 } 54 Fraction add(const Fraction &s1, const Fraction &s2){ 55 return Fraction(s1.up * s2.down + s2.up * s1.down, s1.down * s2.down); 56 } 57 Fraction sub(const Fraction &s1, const Fraction &s2){ 58 return Fraction(s1.up * s2.down - s2.up * s1.down, s1.down * s2.down); 59 } 60 Fraction mul(const Fraction &s1, const Fraction &s2){ 61 return Fraction(s1.up*s2.up,s1.down*s2.down); 62 } 63 Fraction div(const Fraction &s1, const Fraction &s2) 64 { 65 if(s2.up==0) 66 return Fraction(s2.down,0); 67 return Fraction(s1.up * s2.down, s1.down * s2.up); 68 }
问题回答:分数的输出和计算, output/add/sub/mul/div ,你选择的是哪一种设计方案?(友元/自由函数/命名空间+自由函数/类+static)你的决策理由?
如友元方案的优缺点、静态成员函数方案的适用场景、命名空间方案的考虑因素等。
答:选的友元。
理由:可以访问私有成员,简单高效;
优点:可以访问私有成员,简单高效,运行效率高;缺点:会一定程度破坏封装性。

浙公网安备 33010602011771号