实验2

实验任务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();

源代码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 }

源代码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 }

运行测试结果截图

屏幕截图 2025-10-22 090146

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

原因:友元函数声明只是授予函数访问类私有成员的权限,而不会将函数引入全局作用域,因此main函数无法找到func的声明。

问题2:
T.h中,line9-12给出了各种构造函数、析构函数。总结它们各自的功能、调用时机。
答:普通构造函数在创建新对象时调用;复制构造函数在用已有对象初始化新对象时调用;移动构造函数在用临时对象初始化新对象时调用以提升效率;析构函数在对象销毁时自动调用以释放资源。
问题3:
T.cpp中,line13-15,剪切到T.h的末尾,重新编译,程序能否正确编译。如不能,以截图形式给出报错信息,分析原因。
答:不能正确编译,报错信息如下
屏幕截图 2025-10-24 103411

原因:静态成员变量在类外定义(初始化)时,如果放在头文件中,当多个 .cpp 文件包含该头文件时,会导致重复定义,违反了C++的单一定义规则。

实验任务2

源代码Complex.h

 1 #pragma once
 2 #include<string>
 3 
 4 class Complex {
 5     // 类属性
 6 public:
 7     static const std::string doc;
 8     //对象属性
 9 private:
10     double real;
11     double imag;
12     //对象方法
13 public:
14     //构造函数
15     Complex(double r = 0.0, double i = 0.0); //普通构造函数
16     Complex(const Complex& c1);  //复制构造函数
17     //接口
18     double get_real() const;
19     double get_imag() const;
20     void add(const Complex& c1);
21     //友元函数
22     friend void output(const Complex& c);
23     friend double abs(const Complex& c);
24     friend Complex add(const Complex& c1, const Complex& c2);
25     friend bool is_equal(const Complex& c1, const Complex& c2);
26     friend bool is_not_equal(const Complex& c1, const Complex& c2);
27 
28 };
29 
30 //友元函数声明
31 void output(const Complex& c);
32 double abs(const Complex& c);
33 Complex add(const Complex& c1, const Complex& c2);
34 bool is_equal(const Complex& c1, const Complex& c2);
35 bool is_not_equal(const Complex& c1, const Complex& c2);

源代码Complex.cpp

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

源代码task2.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     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 << endl;
24 
25     cout << "Complex对象测试: " << endl;
26     Complex c1;
27     Complex c2(3, -4);
28     Complex c3(c2);
29     Complex c4 = c2;
30     const Complex c5(3.5);
31 
32     cout << "c1 = "; output(c1); cout << endl;
33     cout << "c2 = "; output(c2); cout << endl;
34     cout << "c3 = "; output(c3); cout << endl;
35     cout << "c4 = "; output(c4); cout << endl;
36     cout << "c5.real = " << c5.get_real()
37         << ", c5.imag = " << c5.get_imag() << endl << endl;
38 
39     cout << "复数运算测试: " << endl;
40     cout << "abs(c2) = " << abs(c2) << endl;
41     c1.add(c2);
42     cout << "c1 += c2, c1 = "; output(c1); cout << endl;
43     cout << boolalpha;
44     cout << "c1 == c2 : " << is_equal(c1, c2) << endl;
45     cout << "c1 != c2 : " << is_not_equal(c1, c2) << endl;
46     c4 = add(c2, c3);
47     cout << "c4 = c2 + c3, c4 = "; output(c4); cout << endl;
48 }
49 
50 void test_std_complex() {
51     using std::cout;
52     using std::endl;
53     using std::boolalpha;
54 
55     cout << "std::complex<double>对象测试: " << endl;
56     std::complex<double> c1;
57     std::complex<double> c2(3, -4);
58     std::complex<double> c3(c2);
59     std::complex<double> c4 = c2;
60     const std::complex<double> c5(3.5);
61 
62     cout << "c1 = " << c1 << endl;
63     cout << "c2 = " << c2 << endl;
64     cout << "c3 = " << c3 << endl;
65     cout << "c4 = " << c4 << endl;
66 
67     cout << "c5.real = " << c5.real()
68         << ", c5.imag = " << c5.imag() << endl << endl;
69 
70     cout << "复数运算测试: " << endl;
71     cout << "abs(c2) = " << abs(c2) << endl;
72     c1 += c2;
73     cout << "c1 += c2, c1 = " << c1 << endl;
74     cout << boolalpha;
75     cout << "c1 == c2 : " << (c1 == c2) << endl;
76     cout << "c1 != c2 : " << (c1 != c2) << endl;
77     c4 = c2 + c3;
78     cout << "c4 = c2 + c3, c4 = " << c4 << endl;
79 }

运行结果测试截图

屏幕截图 2025-10-24 153535

问题1:
比较自定义类 Complex 和标准库模板类 complex 的用法,在使用形式上,哪一种更简洁?函数和运算内在有关联吗?
答:(1)标准库 complex 在使用形式上明显更简洁,因为它使用运算符重载,代码更接近数学表达式也更加直观自然。同时标准库能与C++语言特性更好集成,比如流操作,因此也更加方便。
     (2)函数和运算有紧密的内在关联,它们实现相同的数学运算,只是封装和调用方式不同,或者说接口的形式不同。
问题2:
2-1:自定义 Complex 中, output/abs/add/ 等均设为友元,它们真的需要访问 私有数据 吗?(回答“是/否”并给出理由)

答:是,output 函数直接使用了 c.real 和 c.imag 进行输出,abs 函数使用了 c.real 和 c.imag 计算模长。add 函数使用了 c1.real, c1.imag, c2.real, c2.imag 计算和,这些函数确实需要被声明为友元以便访问 Complex 类的私有数据。

2-2:标准库 std::complex 是否把 abs 设为友元?(查阅 cppreference后回答)

答:否,标准库的 std::abs 函数不是 std::complex 类的友元函数。std::abs 是一个独立的函数模板,它可以接受 std::complex 类型的参数。它通常通过调用 std::complex 的公共成员函数 real() 和 imag() 来访问数据。

2-3:什么时候才考虑使用 friend?总结你的思考。 
 答:1、非成员函数需要访问类的私有或保护成员的时候。2、需要增强封装和保持接口简洁,同时又允许高效地访问内部数据的时候。3、当函数需要同时访问多个私有成员且提供公有getter过于繁琐时。
问题3:
如果构造对象时禁用=形式,即遇到 Complex c4 = c2; 编译报错,类Complex的设计应如何调整?
答:要禁用 complex c4 = c2; 形式,需将复制构造函数声明为 explicit
explicit Complex(const Complex& c1);

explicit 关键字阻止编译器在隐式转换和拷贝初始化中使用该构造函数

实验任务3
源代码PlayerControl.h
 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.cpp

 1 #include "PlayerControl.h"
 2 #include <iostream>
 3 #include <algorithm>
 4 int PlayerControl::total_cnt = 0;
 5 PlayerControl::PlayerControl() {}
 6 
 7 ControlType PlayerControl::parse(const std::string& control_str) {
 8     // 1. 将输入字符串转为小写,实现大小写不敏感
 9     std::string lower_str;
10     for (char c : control_str)
11         lower_str += std::tolower(c);
12     // 2. 匹配命令并返回对应枚举
13     ControlType result;
14 
15     if (lower_str == "play") {
16         result = ControlType::Play;
17     }
18     else if (lower_str == "pause") {
19         result = ControlType::Pause;
20     }
21     else if (lower_str == "next") {
22         result = ControlType::Next;
23     }
24     else if (lower_str == "prev") {
25         result = ControlType::Prev;
26     }
27     else if (lower_str == "stop") {
28         result = ControlType::Stop;
29     }
30     else {// 3. 未匹配的字符串返回ControlType::Unknown
31         result = ControlType::Unknown;
32     }
33     // 4. 每次成功调用parse时递增total_cnt
34     if (result != ControlType::Unknown) {
35         total_cnt++;
36     }
37     return result;
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 }

源代码task3.cpp

 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 int main() {
16     test();
17 }

运行结果测试截图

屏幕截图 2025-10-24 221757

实验任务4

源代码Fraction.h

 1 #pragma once
 2 #include <string>
 3 #include <iostream>
 4 
 5 class Fraction {
 6 public:
 7     // 类属性
 8     static const std::string doc; 
 9 
10     // 构造函数
11     Fraction(int u = 0, int d = 1);
12     Fraction(const Fraction& f); 
13 
14     // 接口
15     int get_up() const;     
16     int get_down() const;   
17     Fraction negative() const; 
18 
19 private:
20     // 对象属性 
21     int up;
22     int down;
23 
24     // 友元函数
25     friend void output(const Fraction& f);
26     friend Fraction add(const Fraction& f1, const Fraction& f2);
27     friend Fraction sub(const Fraction& f1, const Fraction& f2);
28     friend Fraction mul(const Fraction& f1, const Fraction& f2);
29     friend Fraction div(const Fraction& f1, const Fraction& f2);
30 };
31 
32 // 工具函数声明 (使用友元函数方案)
33 void output(const Fraction& f); //
34 Fraction add(const Fraction& f1, const Fraction& f2); //
35 Fraction sub(const Fraction& f1, const Fraction& f2); //
36 Fraction mul(const Fraction& f1, const Fraction& f2); //
37 Fraction div(const Fraction& f1, const Fraction& f2); //

源代码Fraction.cpp

 1 #include "Fraction.h"
 2 #include <iostream>
 3 
 4  //辅助函数: 最大公约数 
 5  int gcd(int a, int b) {
 6      while (b) {
 7          a %= b;
 8          std::swap(a, b);
 9      }
10      return a;
11  }
12 
13 // 类属性初始化
14 const std::string Fraction::doc = "Fraction类 v 0.01版. 目前仅支持分数对象的构造、输出、加/减/乘/除运算.";
15 
16 // 构造函数实现
17 Fraction::Fraction(int u, int d) : up(u), down(d) {
18     if (down == 0) {
19         return;
20     }
21     if (down < 0) {
22         up = -up;
23         down = -down;
24     }
25     int common = gcd(std::abs(up), down);
26     up /= common;
27     down /= common;
28 }
29 
30 Fraction::Fraction(const Fraction& f) : up(f.up), down(f.down) {} // 拷贝构造函数
31 
32 // 接口实现
33 int Fraction::get_up() const { return up; } 
34 int Fraction::get_down() const { return down; } 
35 Fraction Fraction::negative() const {
36     return Fraction(-up, down); 
37 }
38 
39 // 友元工具函数实现
40 // 输出分数
41 void output(const Fraction& f) {
42     if (f.down == 0) {
43         std::cout << "分母不能为0";
44     }
45     else if (f.down == 1) {
46         std::cout << f.up;
47     }
48     else {
49         std::cout << f.up << "/" << f.down; // 输出化简后的形式
50     }
51 }
52 
53 Fraction add(const Fraction& f1, const Fraction& f2) {
54     int new_up = f1.up * f2.down + f2.up * f1.down;
55     int new_down = f1.down * f2.down;
56     return Fraction(new_up, new_down); 
57 }
58 
59 Fraction sub(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 mul(const Fraction& f1, const Fraction& f2) {
66     int new_up = f1.up * f2.up;
67     int new_down = f1.down * f2.down;
68     return Fraction(new_up, new_down);
69 }
70 
71 Fraction div(const Fraction& f1, const Fraction& f2) {
72     if (f2.up == 0) {
73         // 返回一个分母为 0 的特殊 Fraction 对象
74         return Fraction(0, 0);
75     }
76     int new_up = f1.up * f2.down;
77     int new_down = f1.down * f2.up;
78     return Fraction(new_up, new_down); // 返回化简后的分数
79 }

源代码task4.cpp

 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 }

运行结果测试截图

屏幕截图 2025-10-25 005429

问题回答:
分数的输出和计算, output/add/sub/mul/div ,你选择的是哪一种设计方案?(友元/自由函数/命名空间+自由函数/类+static)你的决策理由?如友元方案的优缺点、静态成员函数方案的适用场景、命名空间方案的考虑因素等。

答:我选择使用友元函数因为:1. 直接访问私有成员 (up, down),实现分数运算高效简洁。 2. 保持函数调用形式 (如add(f1, f2)) 的数学对称性和自然性。 3.二元操作天然是对称的,自友元函数可以更好地体现这种对称性,使两个操作数处于平等的地位。

posted @ 2025-10-28 13:53  木辛梓  阅读(8)  评论(1)    收藏  举报