实验二

1.实验任务一

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();
View Code

 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 }
View Code

 task1.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 }
View Code

 

运行结果截图如下

屏幕截图 2025-10-22 083817

问题1:程序无法正常运行,报错信息如下,显示func函数在前面没有声明,这是因为友元函数声明只是声明这个函数是友元函数,但函数本身还是要单独声明一下

屏幕截图 2025-10-26 181847

问题2:T(int x = 0, int y = 0)是普通构造函数,功能是给m1,m2赋值,然后计数器cnt加1,被调用的时候显示“T constructor called”。当T对象没有参数,或者是有一个两个参数的时候调用;

             T(const T &t)是复制构造函数,功能是复制已有对象的值给一个新的对象,计数器加1,被调用的时候显示“T copy constructor called”。当新的对象要复制已有对象值的时候调用;

             T(T &&t)是移动构造函数,功能是将一个已有的T对象数据转移给新的这个对象,计数器加1,被调用时显示出“T move constructor called”。当要转移数据来初始化的时候调用;

             ~T()是析构函数,功能是释放对象在生命周期里占的内存,计数器减1,被调用时显示“T destructor called”。当对象的生命周期结束的时候调用。

问题3:无法正确编译,报错截图如下,报错原因是静态成员变量应该在类外初始化,把第八至第十行从T.cpp里面拿到T.h里面,不属于在类外定义和初始化,因此会报错。

屏幕截图 2025-10-26 185431

 

2.实验任务二

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 &c);
12  
13     double get_real() const;
14     double get_imag() const;
15     void add(const Complex &c);
16  
17     friend void output(const Complex &c);
18     friend double abs(const Complex &c);
19     friend Complex add(const Complex &c1, const Complex &c2);
20     friend bool is_equal(const Complex &c1, const Complex &c2);
21     friend bool is_not_equal(const Complex &c1, const Complex &c2);
22  
23 private:
24     double real, imag;
25 };
26 void output(const Complex &c);
27 double abs(const Complex &c);
28 Complex add(const Complex &c1, const Complex &c2);
29 bool is_equal(const Complex &c1, const Complex &c2);
30 bool is_not_equal(const Complex &c1, const Complex &c2);
View Code

Complex.cpp代码如下

 1 #include"Complex.h"
 2 #include<cmath> 
 3 #include<iostream> 
 4 const std::string Complex::doc="a simplified complex class";
 5 Complex::Complex():real(0.0),imag(0.0){}
 6 Complex::Complex(double r):real(r),imag(0.0){}
 7 Complex::Complex(double r,double i):real(r),imag(i){}
 8 Complex::Complex(const Complex&c):real(c.real),imag(c.imag){}
 9 double Complex:: get_real() const
10 {
11     return real;
12 }
13 double Complex:: get_imag() const
14 {
15     return imag;
16 }
17 void Complex::add(const Complex&c)
18 {
19     real+=c.real;
20     imag+=c.imag;
21 }
22 void output(const Complex&c)
23 {
24     if(c.imag>=0)
25     {
26         std::cout<<c.real<<"+"<<c.imag<<"i";
27     }
28     else
29     {
30         std::cout<<c.real<<"-"<<-c.imag<<"i";
31     }
32 }
33 Complex add(const Complex&c1,const Complex&c2)
34 {
35     return Complex(c1.real+c2.real,c1.imag+c2.imag);
36 }
37 double abs(const Complex&c)
38 {
39     return sqrt(c.real*c.real+c.imag*c.imag);
40 }
41 bool is_equal(const Complex&c1,const Complex&c2)
42 {
43     return(c1.real==c2.real)&&(c1.imag==c2.imag);
44 }
45 bool is_not_equal(const Complex&c1,const Complex&c2)
46 {
47     return !is_equal(c1,c2);
48 }
View Code

task2代码如下

 1 #include <iostream>
 2 #include <iomanip>
 3 #include <complex>
 4 #include "Complex.h"
 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 
17 void test_Complex() {
18     using std::cout;
19     using std::endl;
20     using std::boolalpha;
21 
22     cout << "类成员测试: " << endl;
23     cout << Complex::doc << endl 
24     << endl;
25 
26     cout << "Complex对象测试: " << endl;
27     Complex c1;
28     Complex c2(3, -4);
29     Complex c3(c2);
30     Complex c4 = c2;
31     const Complex c5(3.5);
32 
33     cout << "c1 = "; output(c1); cout << endl;
34     cout << "c2 = "; output(c2); cout << endl;
35     cout << "c3 = "; output(c3); cout << endl;
36     cout << "c4 = "; output(c4); cout << endl;
37     cout << "c5.real = " << c5.get_real() 
38          << ", c5.imag = " << c5.get_imag() << endl << endl;
39 
40     cout << "复数运算测试: " << endl;
41     cout << "abs(c2) = " << abs(c2) << endl;
42     c1.add(c2);
43     cout << "c1 += c2, c1 = "; output(c1); cout << endl;
44     cout << boolalpha;
45     cout << "c1 == c2 : " << is_equal(c1, c2) << endl;
46     cout << "c1 != c2 : " << is_not_equal(c1, c2) << endl;
47     c4 = add(c2, c3);
48     cout << "c4 = c2 + c3, c4 = "; output(c4); cout << endl;
49 }
50 
51 void test_std_complex() {
52     using std::cout;
53     using std::endl;
54     using std::boolalpha;
55 
56     cout << "std::complex<double>对象测试: " << endl;
57     std::complex<double> c1;
58     std::complex<double> c2(3, -4);
59     std::complex<double> c3(c2);
60     std::complex<double> c4 = c2;
61     const std::complex<double> c5(3.5);
62 
63     cout << "c1 = " << c1 << endl;
64     cout << "c2 = " << c2 << endl;
65     cout << "c3 = " << c3 << endl;
66     cout << "c4 = " << c4 << endl;
67 
68     cout << "c5.real = " << c5.real() 
69          << ", c5.imag = " << c5.imag() << endl << endl;
70 
71     cout << "复数运算测试: " << endl;
72     cout << "abs(c2) = " << abs(c2) << endl;
73     c1 += c2;
74     cout << "c1 += c2, c1 = " << c1 << endl;
75     cout << boolalpha;
76     cout << "c1 == c2 : " << (c1 == c2)<< endl;
77     cout << "c1 != c2 : " << (c1 != c2) << endl;
78     c4 = c2 + c3;
79     cout << "c4 = c2 + c3, c4 = " << c4 << endl;
80     system("pause");
81 }
View Code

运行截图如下

 屏幕截图 2025-10-24 184653屏幕截图 2025-10-24 184700

问题1:标准库模板类 complex 更简洁。有关联,因为标准库模板类 complex 使用了运算符重载

问题2:2-1  需要,因为abs,is_equal等函数需要用到复数的实部和虚部,实部和虚部是私有数据

             2-2  经过查阅,std::complex 没有把 abs 设为友元

             2-3  我觉得当需要访问私有数据的时候,需要用到friend

问题3:禁用=形式,想要实现Complex c4 = c2;那就不能让编译器调用拷贝构造函数,因此可以把拷贝构造函数设为private,这样就不会报错了

 

 

3.实验任务三

 PlayerControl.h的代码如下

 1 #pragma once
 2 #include <string>
 3 enum class ControlType {Play,Pause,Next,Prev,Stop,Unknown};
 4 class PlayerControl{
 5     private:
 6         static int total_cnt;
 7     public:
 8         PlayerControl();
 9         static int get_cnt;
10         ControlType parse(const std::string& control_str); 
11         void execute(ControlType cmd) const
12 };
View Code

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     // 1. 将输入字符串转为小写,实现大小写不敏感
11     std::string lower_str;
12     for(auto &c:control_str){
13         char ch=tolower(c);
14         lower_str+=ch;
15     }
16     // 2. 匹配"play"/"pause"/"next"/"prev"/"stop"并返回对应枚举
17     ControlType cmd=ControlType::Unknown;
18     if(lower_str=="play"){
19         cmd=ControlType::Play;
20         total_cnt++;
21     }else if(lower_str=="pause"){
22         cmd=ControlType::Pause;
23         total_cnt++;
24     }else if(lower_str=="next"){
25         cmd=ControlType::Next;
26         total_cnt++;
27     }else if(lower_str=="prev"){
28         cmd=ControlType::Prev;
29         total_cnt++;
30     }else if(lower_str=="stop"){
31         cmd=ControlType::Stop;
32         total_cnt++;
33     }else{
34         cmd=ControlType::Unknown;
35     }
36     return cmd;
37 }
38 
39 
40 void PlayerControl::execute(ControlType cmd) const {
41     switch (cmd) {
42     case ControlType::Play:  std::cout << "[play] Playing music...\n"; break;
43     case ControlType::Pause: std::cout << "[Pause] Music paused\n";    break;
44     case ControlType::Next:  std::cout << "[Next] Skipping to next track\n"; break;
45     case ControlType::Prev:  std::cout << "[Prev] Back to previous track\n"; break;
46     case ControlType::Stop:  std::cout << "[Stop] Music stopped\n"; break;
47     default:                 std::cout << "[Error] unknown control\n"; break;
48     }
49 }
50 
51 int PlayerControl::get_cnt() {
52     return total_cnt;
53 }
View Code

task3.cpp代码如下

 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 }
View Code

运行结果截图如下

屏幕截图 2025-10-25 113407

 

 

4.实验任务四

Fraction.h代码如下

 1 #pragma once
 2 #include <string>
 3 
 4 class Fraction{
 5     private:
 6         int up,down;
 7         void simplify();
 8     public:
 9         static const std::string doc;
10         Fraction(int up);
11         Fraction(int up,int down);
12         Fraction(const Fraction &f);
13         int get_up() const;
14         int get_down() const;
15         Fraction negative() const;        
16 };
17 //命名空间+自由函数 
18 namespace FractionTool{
19     void output(const Fraction &f);
20     Fraction add(const Fraction &f1,const Fraction &f2);
21     Fraction sub(const Fraction &f1,const Fraction &f2);
22     Fraction mul(const Fraction &f1,const Fraction &f2);
23     Fraction div(const Fraction &f1,const Fraction &f2);
24 }    
View Code

Fraction.cpp代码如下

 1 #include "Fraction.h"
 2 #include<iostream>
 3 #include<cstdlib>
 4 const std::string Fraction::doc="Fraction类 v0.01版本,目前仅支持分数对象的构造、输出、加/减/乘/除运算";
 5 Fraction::Fraction(int up):up(up),down(1){}
 6 Fraction::Fraction(int up,int down):up(up),down(down){
 7     simplify();
 8 }
 9 Fraction::Fraction(const Fraction &f):up(f.up),down(f.down){
10     simplify();
11 }
12 int Fraction::get_up() const{
13     return up;
14 }
15 int Fraction::get_down() const{
16     return down;
17 }
18 Fraction Fraction::negative() const{
19     return Fraction(-up,down);
20 }
21 
22 int gcd(int a,int b){
23     a=std::abs(a);
24     b=std::abs(b);
25     while(b!=0){
26         int temp=b;
27         b=a%b;
28         a=temp;
29     }
30     return a;
31 }
32 
33 void Fraction::simplify(){
34     if(down<0){
35         up=-up;
36         down=-down;
37     }
38     int gongyueshu=gcd(up,down);
39     if(gongyueshu!=0){
40         up/=gongyueshu;
41         down/=gongyueshu;
42     }
43 }
44  namespace FractionTool{
45      void output(const Fraction &f){
46          if(f.get_down()==1){
47              std::cout<<f.get_up();
48          }else if(f.get_down()==0){
49              std::cout<<"分母不能为0"; 
50          }else if(f.get_up()==0){
51              std::cout<<"0";
52          } else{
53              std::cout<<f.get_up()<<"/"<<f.get_down();
54          }
55      }
56      Fraction add(const Fraction &f1,const Fraction &f2){
57          int newup=f1.get_up()*f2.get_down()+f2.get_up()*f1.get_down();
58          int newdown=f1.get_down()*f2.get_down();
59          return Fraction(newup,newdown);
60      }
61      Fraction sub(const Fraction &f1,const Fraction &f2){
62          int newup=f1.get_up()*f2.get_down()-f2.get_up()*f1.get_down();
63          int newdown=f1.get_down()*f2.get_down();
64          return Fraction(newup,newdown);
65      }
66      Fraction mul(const Fraction &f1,const Fraction &f2){
67          int newup=f1.get_up()*f2.get_up();
68          int newdown=f1.get_down()*f2.get_down();
69          return Fraction(newup,newdown);
70      }
71      Fraction div(const Fraction &f1,const Fraction &f2){
72          int newup=f1.get_up()*f2.get_down();
73          int newdown=f1.get_down()*f2.get_up();
74          return Fraction(newup,newdown);
75      }
76  }
View Code

task4.cpp代码如下

 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     using namespace FractionTool;   
19 
20     cout << "Fraction类测试: " << endl;
21     cout << Fraction::doc << endl << endl;
22 
23     Fraction f1(5);
24     Fraction f2(3, -4), f3(-18, 12);
25     Fraction f4(f3);
26     cout << "f1 = "; output(f1); cout << endl;
27     cout << "f2 = "; output(f2); cout << endl;
28     cout << "f3 = "; output(f3); cout << endl;
29     cout << "f4 = "; output(f4); cout << endl;
30 
31     const Fraction f5(f4.negative());
32     cout << "f5 = "; output(f5); cout << endl;
33     cout << "f5.get_up() = " << f5.get_up() 
34         << ", f5.get_down() = " << f5.get_down() << endl;
35 
36     cout << "f1 + f2 = "; output(add(f1, f2)); cout << endl;
37     cout << "f1 - f2 = "; output(sub(f1, f2)); cout << endl;
38     cout << "f1 * f2 = "; output(mul(f1, f2)); cout << endl;
39     cout << "f1 / f2 = "; output(div(f1, f2)); cout << endl;
40     cout << "f4 + f5 = "; output(add(f4, f5)); cout << endl;
41 }
42 
43 void test2() {
44     using std::cout;
45     using std::endl;
46     using namespace FractionTool; 
47 
48     Fraction f6(42, 55), f7(0, 3);
49     cout << "f6 = "; output(f6); cout << endl;
50     cout << "f7 = "; output(f7); cout << endl;
51     cout << "f6 / f7 = "; output(div(f6, f7)); cout << endl;
52 }
View Code

运行结果如下

屏幕截图 2025-10-25 154931

问题:我选择的实现方式是命名空间+自由函数的形式,因为考虑到现在是Fraction类 v 0.01版,以后Fraction可能还要实现更多更加复杂的计算,那么到时候就可以在FractionTool里面直接添加函数即可,不用去修改Fraction类,更加方便,扩展性更强,并且我个人觉得用命名空间+自由函数的形式可以使代码看上去条理清晰,职责更加分明。

posted @ 2025-10-26 19:05  nonono小酷宝  阅读(7)  评论(0)    收藏  举报