实验二 现代C++编程初体验

任务1:

源代码:

 1 #pragma once
 2 #include <string>
 3 // 类T: 声明
 4 class T {
 5 // 对象属性、方法
 6 public:
 7     T(int x = 0, int y = 0); // 普通构造函数
 8     T(const T &t); // 复制构造函数
 9     T(T &&t); // 移动构造函数
10     ~T(); // 析构函数
11     
12     void adjust(int ratio); // 按系数成倍调整数据
13     void display() const; // 以(m1, m2)形式显示T类对象信息
14     
15 private:
16     int m1, m2;
17     
18 // 类属性、方法
19 public:
20     static int get_cnt(); // 显示当前T类对象总数
21     
22 public:
23     static const std::string doc; // 类T的描述信息
24     static const int max_cnt; // 类T对象上限
25     
26 private:
27     static int cnt; // 当前T类对象数目
28     
29 // 类T友元函数声明
30     friend void func();
31 };
32 
33 // 普通函数声明
34 void func();
T.h
 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 }
T.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 }
task1.cpp

运行结果截图:

屏幕截图 2025-10-27 163434

问题1:

屏幕截图 2025-10-27 164106

原因:友元函数的声明只是告知编译器该函数是类的友元,但函数本身的定义(或声明)仍需在外部提供。如果去掉 T.h 中的 void func(); 声明,编译器在编译调用 func() 的代码(如 task1.cpp 中的 func(); )时,会因找不到 func() 的声明而报错,提示“未声明的标识符”之类的编译错误。

问题2:

1.  line9( T(int x = 0, int y = 0) ;):

 功能:普通构造函数,创建 T 类对象时初始化成员变量 m1 和 m2 ,支持默认参数(无参或传参创建对象)。

 调用时机:当用 T t1; (无参)、 T t2(3,4); (传参)方式创建对象时调用。

2.  line10( T(const T &t) ;):

 功能:复制构造函数,用一个已存在的 T 类对象拷贝创建新的 T 类对象,复制成员变量的值。

 调用时机:当用已存在的对象初始化新对象时调用,例如 T t3(t2); (直接初始化)、按值传递对象参数、函数返回对象(某些情况)等。

3.  line11( T(T &&t) ;):

 功能:移动构造函数,用一个临时对象的资源“移动”创建新的 T 类对象,避免不必要的拷贝,提高效率。

 调用时机:当用临时对象(如 std::move(t2) 转换后的对象)初始化新对象时调用,例如 T t4(std::move(t2)); 。

4.  line12 析构函数( ~T(); ):

功能:析构函数,在 T 类对象生命周期结束时(如离开作用域),释放对象占用的资源(本题中主要是维护静态成员 cnt 的计数)。

 调用时机:对象销毁时自动调用,例如局部对象离开作用域、动态分配的对象被 delete 时。

问题三:

屏幕截图 2025-10-27 172650

 

int T::get_cnt() 是类的静态成员函数,其实现依赖于类的静态成员 cnt 。静态成员函数的声明必须在类内部( T.h 中 static int get_cnt(); ),而实现可以在类外。如果将 line13-15 ( get_cnt 的实现)剪切到 T.h 末尾,会导致:

1.类的声明和实现混杂;
2.get_cnt 函数内部访问了静态成员 cnt ,而 cnt 的定义在 T.cpp 中,若将 get_cnt 的实现移到 T.h ,会导致链接时找不到 cnt 的定义,出现“未定义的引用”错误。

 

任务2:

源代码:

 1 //
 2 #include "Complex.h"
 3 #include <iostream>
 4 #include <iomanip>
 5 #include <complex>
 6 
 7 void test_Complex();
 8 void test_std_complex();
 9 
10 int main() {
11     std::cout << "******测试1:自定义类Complex******\n";
12     test_Complex();
13 
14     std::cout << "\n******测试2:标准库模板类complex******\n";
15     test_std_complex();
16     return 0;
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     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 }
task2.cpp
 1 #pragma once
 2 #include <string>
 3 #include <cmath>
 4 
 5 class Complex {
 6 public:
 7     static const std::string doc;
 8 
 9     Complex(double real = 0.0, double imag = 0.0);
10     Complex(const Complex &other);
11 
12     double get_real() const;
13     double get_imag() const;
14     void add(const Complex &other);
15 
16     friend void output(const Complex &c);
17     friend double abs(const Complex &c);
18     friend Complex add(const Complex &c1, const Complex &c2);
19     friend bool is_equal(const Complex &c1, const Complex &c2);
20     friend bool is_not_equal(const Complex &c1, const Complex &c2);
21 
22 private:
23     double m_real;
24     double m_imag;
25 };
complex.h
 1 #include "Complex.h"
 2 #include <iostream>
 3 #include<cmath>
 4 #include<string>
 5 
 6 // 静态成员初始化
 7 const std::string Complex::doc = "a simplified Complex class";
 8 
 9 // 构造函数实现
10 Complex::Complex(double real, double imag) : m_real(real), m_imag(imag) {}
11 Complex::Complex(const Complex &other) : m_real(other.m_real), m_imag(other.m_imag) {}
12 
13 // 成员函数实现
14 double Complex::get_real() const { return m_real; }
15 double Complex::get_imag() const { return m_imag; }
16 void Complex::add(const Complex &other) {
17     m_real += other.m_real;
18     m_imag += other.m_imag;
19 }
20 
21 // 友元函数实现
22 void output(const Complex &c) {
23     std::cout << c.m_real << (c.m_imag >= 0 ? " + " : " - ") 
24               << std::abs(c.m_imag) << "i";
25 }
26 
27 double abs(const Complex &c) {
28     return std::sqrt(c.m_real * c.m_real + c.m_imag * c.m_imag);
29 }
30 
31 Complex add(const Complex &c1, const Complex &c2) {
32     return Complex(c1.m_real + c2.m_real, c1.m_imag + c2.m_imag);
33 }
34 
35 bool is_equal(const Complex &c1, const Complex &c2) {
36     return (c1.m_real == c2.m_real) && (c1.m_imag == c2.m_imag);
37 }
38 
39 bool is_not_equal(const Complex &c1, const Complex &c2) {
40     return !is_equal(c1, c2);
41 }
complex.cpp

问题1:标准库模板类 complex 更简洁。函数和运算内在有关联,标准库通过运算符重载、内置函数等方式,让复数操作更贴近数学直觉,而自定义类需通过成员函数或全局函数间接实现,形式上更繁琐。

问题2:1.是,output 需要访问 m_real 和 m_imag 来格式化输出; abs 需要访问实部和虚部计算模长; add 需要访问两个复数的实部、虚部来做加法。这些函数若不设为友元,无法直接访问类的私有成员。    

2.否,标准库 std::complex 的 abs 是通过全局函数实现的,它不需要成为友元,因为 std::complex 的实部和虚部可以通过 real() 和 imag() 成员函数公开获取, abs 函数通过这两个公开接口即可计算模长。

3.当外部函数(或类)需要直接访问类的私有成员,且这种访问是必要且合理的(如运算符重载、格式化输出、数学运算等场景),才考虑使用 friend 。

问题3:若要禁用 Complex c4 = c2; 形式的拷贝(即禁用拷贝构造函数),可以将拷贝构造函数设为私有且不实现,或者使用C++11及以上特性将其删除( = delete )。

 

任务3:

源代码:

 1 #include "PlayerControl.h"
 2 #include <iostream>
 3 void test() {
 4     PlayerControl controller;
 5     std::string control_str;
 6     std::cout << "Enter Control: (play/pause/next/prev/stop/quit):\n";
 7     while(std::cin >> control_str) {
 8         if(control_str == "quit")
 9             break;
10         ControlType cmd = controller.parse(control_str);
11         controller.execute(cmd);
12         std::cout << "Current Player control: " << PlayerControl::get_cnt() << "\n\n";
13     }
14 }
15 
16 int main() {
17     test();
18 }
task3.cpp
 1 #pragma once
 2 #include <string>
 3 enum class ControlType {Play, Pause, Next, Prev, Stop, Unknown};
 4 class PlayerControl {
 5 public:
 6     PlayerControl();
 7     ControlType parse(const std::string& control_str); // 实现std::string -->ControlType转换
 8     void execute(ControlType cmd) const; // 执行控制操作(以打印输出模拟)
 9     static int get_cnt();
10     private:
11     static int total_cnt;
12 };
PlayerControl.h
 1 #include "PlayerControl.h"
 2 #include <iostream>
 3 #include <algorithm>
 4 int PlayerControl::total_cnt = 0;
 5 PlayerControl::PlayerControl() {}
 6 // 待补足
 7 // 1. 将输入字符串转为小写,实现大小写不敏感
 8 // 2. 匹配"play"/"pause"/"next"/"prev"/"stop"并返回对应枚举
 9 // 3. 未匹配的字符串返回ControlType::Unknown
10 // 4. 每次成功调用parse时递增total_cnt
11 ControlType PlayerControl::parse(const std::string& control_str) {
12     // xxx
13     // 1. 将输入字符串转为小写,实现大小写不敏感
14      std::string lower_str = control_str;
15      std::transform(lower_str.begin(), lower_str.end(), lower_str.begin(),
16                     [](unsigned char c) { return std::tolower(c); });
17      
18      // 2. 匹配命令并返回对应枚举值
19      ControlType cmd = ControlType::Unknown;
20      if (lower_str == "play") {
21          cmd = ControlType::Play;
22      } else if (lower_str == "pause") {
23          cmd = ControlType::Pause;
24      } else if (lower_str == "next") {
25          cmd = ControlType::Next;
26      } else if (lower_str == "prev") {
27          cmd = ControlType::Prev;
28      } else if (lower_str == "stop") {
29          cmd = ControlType::Stop;
30      }
31      
32      // 3. 每次成功调用parse时递增total_cnt(Unknown类型不计数)
33      if (cmd != ControlType::Unknown) {
34          total_cnt++;
35      }
36      return cmd;
37  
38 }
39 void PlayerControl::execute(ControlType cmd) const {
40     switch (cmd) {
41         case ControlType::Play: std::cout << "[play] Playing music...\n"; break;
42         case ControlType::Pause: std::cout << "[Pause] Music paused\n"; break;
43         case ControlType::Next: std::cout << "[Next] Skipping to next track\n"; break;
44         case ControlType::Prev: std::cout << "[Prev] Back to previous track\n"; break;
45         case ControlType::Stop: std::cout << "[Stop] Music stopped\n"; break;
46         default: std::cout << "[Error] unknown control\n"; break;
47     }
48 }
49 int PlayerControl::get_cnt() {
50     return total_cnt;
51 }
PlayerControl.cpp

运行结果截图:

屏幕截图 2025-10-27 182742

思考:

把[play]换成音乐符号;

把[Pause]换成暂停符号;

把[Next]换成块快进符号;

把[Prev]换成缩进符号;

把[Stop]换成暂停符号;

 

 

 

任务4

源代码:

 1 #include "Fraction.h"
 2 #include <iostream>
 3 void test1();
 4 void test2();
 5 int main() {
 6     std::cout << "测试1: Fraction类基础功能测试\n";
 7     test1();
 8     std::cout << "\n测试2: 分母为0测试: \n";
 9     test2();
10 }
11 void test1() {
12     using std::cout;
13     using std::endl;
14     cout << "Fraction类测试: " << endl;
15     cout << Fraction::doc << endl << endl;
16     Fraction f1(5);
17     Fraction f2(3, -4), f3(-18, 12);
18     Fraction f4(f3);
19     cout << "f1 = "; output(f1); cout << endl;
20         cout << "f2 = "; output(f2); cout << endl;
21     cout << "f3 = "; output(f3); cout << endl;
22     cout << "f4 = "; output(f4); cout << endl;
23     const Fraction f5(f4.negative());
24     cout << "f5 = "; output(f5); cout << endl;
25     cout << "f5.get_up() = " << f5.get_up()
26     << ", f5.get_down() = " << f5.get_down() << endl;
27     cout << "f1 + f2 = "; output(add(f1, f2)); cout << endl;
28     cout << "f1 - f2 = "; output(sub(f1, f2)); cout << endl;
29     cout << "f1 * f2 = "; output(mul(f1, f2)); cout << endl;
30     cout << "f1 / f2 = "; output(div(f1, f2)); cout << endl;
31     cout << "f4 + f5 = "; output(add(f4, f5)); cout << endl;
32 }
33 void test2() {
34     using std::cout;
35     using std::endl;
36     Fraction f6(42, 55), f7(0, 3);
37     cout << "f6 = "; output(f6); cout << endl;
38     cout << "f7 = "; output(f7); cout << endl;
39     cout << "f6 / f7 = "; output(div(f6, f7)); cout << endl;
40 }
task4.cpp
 1 #include "Fraction.h"
 2 #include <iostream>
 3 #include <algorithm>
 4 #include <stdexcept>
 5 
 6 const std::string Fraction::doc = "Fraction类 v0.01版.\n目前仅支持分数对象的构造、输出、加/减/乘/除运算.";
 7 
 8 int gcd(int a, int b) {
 9     a = std::abs(a);
10     b = std::abs(b);
11     while (b != 0) {
12         int temp = b;
13         b = a % b;
14         a = temp;
15     }
16     return a;
17 }
18 
19 Fraction::Fraction(int up, int down) : m_up(up), m_down(down) {
20     if (down == 0) {
21         throw std::invalid_argument("分母不能为0");
22     }
23     reduce();
24 }
25 
26 Fraction::Fraction(const Fraction &other) : m_up(other.m_up), m_down(other.m_down) {}
27 
28 int Fraction::get_up() const { return m_up; }
29 int Fraction::get_down() const { return m_down; }
30 
31 Fraction Fraction::negative() const {
32     return Fraction(-m_up, m_down);
33 }
34 
35 void Fraction::reduce() {
36     if (m_down < 0) {
37         m_up = -m_up;
38         m_down = -m_down;
39     }
40     int g = gcd(m_up, m_down);
41     if (g != 0) {
42         m_up /= g;
43         m_down /= g;
44     }
45 }
46 
47 void output(const Fraction &f) {
48     if (f.m_down == 1) {
49         std::cout << f.m_up;
50     } else {
51         std::cout << f.m_up << "/" << f.m_down;
52     }
53 }
54 
55 Fraction add(const Fraction &f1, const Fraction &f2) {
56     int up = f1.m_up * f2.m_down + f2.m_up * f1.m_down;
57     int down = f1.m_down * f2.m_down;
58     return Fraction(up, down);
59 }
60 
61 Fraction sub(const Fraction &f1, const Fraction &f2) {
62     int up = f1.m_up * f2.m_down - f2.m_up * f1.m_down;
63     int down = f1.m_down * f2.m_down;
64     return Fraction(up, down);
65 }
66 
67 Fraction mul(const Fraction &f1, const Fraction &f2) {
68     int up = f1.m_up * f2.m_up;
69     int down = f1.m_down * f2.m_down;
70     return Fraction(up, down);
71 }
72 
73 Fraction div(const Fraction &f1, const Fraction &f2) {
74     if (f2.m_up == 0) {
75         std::cout << "分母不能为" ;
76         return Fraction(0,1);
77     }
78     int up = f1.m_up * f2.m_down;
79     int down = f1.m_down * f2.m_up;
80     return Fraction(up, down);
81 }
Fraction.cpp
 1 #pragma once
 2 #include <string>
 3 
 4 class Fraction {
 5 public:
 6     static const std::string doc;
 7 
 8     Fraction(int up = 0, int down = 1);
 9     Fraction(const Fraction &other);
10 
11     int get_up() const;
12     int get_down() const;
13     Fraction negative() const;
14 
15     friend void output(const Fraction &f);
16     friend Fraction add(const Fraction &f1, const Fraction &f2);
17     friend Fraction sub(const Fraction &f1, const Fraction &f2);
18     friend Fraction mul(const Fraction &f1, const Fraction &f2);
19     friend Fraction div(const Fraction &f1, const Fraction &f2);
20 
21 private:
22     void reduce();
23     int m_up;
24     int m_down;
25 };
Fraction.h

运行结果截图:

屏幕截图 2025-10-27 194404

问题回答:

友元方案:

原因:友元函数可直接访问 Fraction 类的私有成员(分子 m_up 、分母 m_down ),无需通过 getter 函数间接获取,既能保证代码简洁性,又能高效实现分数的约分、运算及异常处理(如分母为0的校验)。这种设计在维持类封装性的同时,让外部函数能灵活操作内部数据,非常适配分数运算的场景。

实验总结

本次4个实验,涵盖类的设计与实现,封装性,静态成员,友元函数,多文件组织等知识,让我对面向对象程序设计有了一个更好的认识。

 

posted @ 2025-10-27 21:07  yyzbh  阅读(0)  评论(0)    收藏  举报