实验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 }

##运行结果

image

 ##问题1

Yes

##问题2

普通构造函数  功能:初始化对象的数据成员,为对象分配必要的资源    调用时机:创建新对象时

复制构造函数  功能:通过拷贝另一个同类对象来初始化新对象   调用时机:用已有对象初始化新对象时:T obj1; T obj2(obj1); 对象作为值参数传递给函数时

移动构造函数  功能:通过"窃取"另一个临时对象的资源来初始化新对象   调用时机:用右值(临时对象)初始化新对象时:T obj1; T obj2(std::move(obj1))

析构函数  功能:释放对象占用的资源   调用时机:对象生命周期结束时;对对象调用delete操作时

##问题3

能正确编译

##实验任务2

##代码

##Complex.h

 1 #ifndef COMPLEX_H
 2 #define COMPLEX_H
 3 
 4 #include <string>
 5 
 6 class Complex {
 7 public:
 8     static const std::string doc;  // 类说明文档
 9     
10     // 构造函数
11     Complex();                          // 默认构造函数,创建0+0i
12     Complex(double real);               // 用实部创建复数,虚部为0
13     Complex(double real, double imag);  // 用实部和虚部创建复数
14     Complex(const Complex& other);      // 拷贝构造函数
15     
16     // 成员函数
17     double get_real() const;           // 获取实部
18     double get_imag() const;           // 获取虚部
19     void add(const Complex& other);     // 复数加法,相当于+=
20     
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 private:
29     double real_;  // 实部
30     double imag_;  // 虚部
31 };
32 
33 #endif // COMPLEX_H

##Complex.cpp

 1 #include "Complex.h"
 2 #include <iostream>
 3 #include <cmath>
 4 
 5 using namespace std;
 6 
 7 // 类说明文档定义
 8 const string Complex::doc = "a simplified complex class";
 9 
10 // 默认构造函数
11 Complex::Complex() : real_(0.0), imag_(0.0) {}
12 
13 // 用实部创建复数
14 Complex::Complex(double real) : real_(real), imag_(0.0) {}
15 
16 // 用实部和虚部创建复数
17 Complex::Complex(double real, double imag) : real_(real), imag_(imag) {}
18 
19 // 拷贝构造函数
20 Complex::Complex(const Complex& other) : real_(other.real_), imag_(other.imag_) {}
21 
22 // 获取实部
23 double Complex::get_real() const {
24     return real_;
25 }
26 
27 // 获取虚部
28 double Complex::get_imag() const {
29     return imag_;
30 }
31 
32 // 复数加法(相当于+=)
33 void Complex::add(const Complex& other) {
34     real_ += other.real_;
35     imag_ += other.imag_;
36 }
37 
38 // 输出复数(友元函数)
39 void output(const Complex& c) {
40     cout << c.real_;
41     if (c.imag_ >= 0) {
42         cout << " + " << c.imag_ << "i";
43     } else {
44         cout << " - " << -c.imag_ << "i";
45     }
46 }
47 
48 // 取模(友元函数)
49 double abs(const Complex& c) {
50     return sqrt(c.real_ * c.real_ + c.imag_ * c.imag_);
51 }
52 
53 // 复数相加(友元函数)
54 Complex add(const Complex& c1, const Complex& c2) {
55     return Complex(c1.real_ + c2.real_, c1.imag_ + c2.imag_);
56 }
57 
58 // 判断相等(友元函数)
59 bool is_equal(const Complex& c1, const Complex& c2) {
60     return (c1.real_ == c2.real_) && (c1.imag_ == c2.imag_);
61 }
62 
63 // 判断不等(友元函数)
64 bool is_not_equal(const Complex& c1, const Complex& c2) {
65     return !is_equal(c1, c2);
66 }

##task2.cpp

 1 #include "Complex.h"
 2 #include <iostream>
 3 #include <iomanip>
 4 #include <complex>
 5 
 6 using namespace std;
 7 
 8 void test_Complex();
 9 void test_std_complex();
10 
11 int main() {
12     cout << "*******测试1: 自定义类Complex*******\n";
13     test_Complex();
14     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 }

##运行结果

image

 ##问题1

​​标准库模板类complex明显更简洁,标准库使用自然的数学运算符,自定义类complex需要专门的输出函数;

函数和运算在功能上是完全等价的,只是标准库的写法更接近数学表达式,直观易懂,标准库的设计通过运算符重载实现了更优雅的语法。

##问题2

2.1是,列如,如果仅通过 get_real()和 get_imag()获取数据,output()需要额外逻辑拼接字符串,不如直接访问私有变量高效,如果不直接访问私有数据,可能会导致性能损失,代码冗余​​,封装性降低等,因此,友元函数是合理的设计选择。

2.2标准库 std::complex​​没有​​将 abs()设为友元函数,std::abs(std::complex)是独立函数​​,它​​不依赖友元​​访问 std::complex的私有数据,而是通过 real()和 imag()这两个公共成员函数获取实部和虚部。

2.3需要访问私有数据,但无法通过公有接口高校实现;需要支持运算符重载,但运算符函数不能是成员。

##问题3

Complex c4 = c2是拷贝初始化,如果编译失败,那么使用直接初始化Complex c3(c2)。

##实验任务3

##代码

##PlayControl.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 };

##PlayControl.cpp

 1 #include "PlayerControl.h"
 2 #include <iostream>
 3 #include <algorithm>
 4 #include <cctype>
 5 
 6 int PlayerControl::total_cnt = 0;
 7 
 8 PlayerControl::PlayerControl() {}
 9 
10 ControlType PlayerControl::parse(const std::string& control_str) {
11     // 1. 将输入字符串转为小写(实现大小写不敏感)
12     std::string lower_str = control_str;
13     std::transform(lower_str.begin(), lower_str.end(), lower_str.begin(),
14                    [](unsigned char c) { return std::tolower(c); });
15 
16     // 2. 匹配命令并返回对应枚举
17     ControlType cmd = ControlType::Unknown;
18     if (lower_str == "play") {
19         cmd = ControlType::Play;
20     } else if (lower_str == "pause") {
21         cmd = ControlType::Pause;
22     } else if (lower_str == "next") {
23         cmd = ControlType::Next;
24     } else if (lower_str == "prev") {
25         cmd = ControlType::Prev;
26     } else if (lower_str == "stop") {
27         cmd = ControlType::Stop;
28     }
29 
30     // 3. 成功匹配时,递增总操作次数
31     if (cmd != ControlType::Unknown) {
32         total_cnt++;
33     }
34 
35     return cmd;
36 }
37 
38 void PlayerControl::execute(ControlType cmd) const {
39     switch (cmd) {
40         case ControlType::Play:
41             std::cout << "[play] Playing music...\n";
42             break;
43         case ControlType::Pause:
44             std::cout << "[Pause] Music paused\n";
45             break;
46         case ControlType::Next:
47             std::cout << "[Next] Skipping to next track\n";
48             break;
49         case ControlType::Prev:
50             std::cout << "[Prev] Back to previous track\n";
51             break;
52         case ControlType::Stop:
53             std::cout << "[Stop] Music stopped\n";
54             break;
55         default:
56             std::cout << "[Error] unknown control\n";
57             break;
58     }
59 }
60 
61 int PlayerControl::get_cnt() {
62     return total_cnt;
63 }

##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  
11  ControlType cmd = controller.parse(control_str);
12 controller.execute(cmd);
13  std::cout << "Current Player control: " << PlayerControl::get_cnt() << "\n\n";
14   }
15 }
16 int main(){
17     test();
18 }

##运行结果

image

 ##实验任务4

##代码

##Fraction.h

 1 #ifndef FRACTION_H
 2 #define FRACTION_H
 3 
 4 #include <string>
 5 
 6 class Fraction {
 7 public:
 8     // 类属性,用于类说明
 9     static const std::string doc;
10 
11     // 构造函数
12     Fraction(int up = 0, int down = 1);
13     Fraction(const Fraction& other);
14 
15     // 接口
16     int get_up() const;
17     int get_down() const;
18     Fraction negative() const;
19 
20     // 友元函数声明(工具函数)
21     friend void output(const Fraction& frac);
22     friend Fraction add(const Fraction& f1, const Fraction& f2);
23     friend Fraction sub(const Fraction& f1, const Fraction& f2);
24     friend Fraction mul(const Fraction& f1, const Fraction& f2);
25     friend Fraction div(const Fraction& f1, const Fraction& f2);
26 
27 private:
28     // 对象属性:分子和分母
29     int up;
30     int down;
31 
32     // 内部工具函数:化简分数
33     void simplify();
34     // 内部工具函数:求最大公约数
35     int gcd(int a, int b);
36 };
37 
38 #endif // FRACTION_H

##Fraction.cpp

  1 #include "Fraction.h"
  2 #include <iostream>
  3 
  4 // 初始化类属性
  5 const std::string Fraction::doc = "Fraction类 v0.01版.\n目前仅支持分数对象的构造、输出、加/减/乘/除运算.";
  6 
  7 // 构造函数
  8 Fraction::Fraction(int up, int down) : up(up), down(down) {
  9     if (down == 0) {
 10         std::cerr << "分母不能为0" << std::endl;
 11         // 分母为0时,默认初始化为0/1
 12         this->up = 0;
 13         this->down = 1;
 14     } else {
 15         simplify();
 16     }
 17 }
 18 
 19 // 拷贝构造函数
 20 Fraction::Fraction(const Fraction& other) : up(other.up), down(other.down) {}
 21 
 22 // 获取分子
 23 int Fraction::get_up() const {
 24     return up;
 25 }
 26 
 27 // 获取分母
 28 int Fraction::get_down() const {
 29     return down;
 30 }
 31 
 32 // 求负
 33 Fraction Fraction::negative() const {
 34     return Fraction(-up, down);
 35 }
 36 
 37 // 化简分数
 38 void Fraction::simplify() {
 39     if (up == 0) {
 40         down = 1;
 41         return;
 42     }
 43     int sign = 1;
 44     if (up < 0) {
 45         sign *= -1;
 46         up = -up;
 47     }
 48     if (down < 0) {
 49         sign *= -1;
 50         down = -down;
 51     }
 52     int g = gcd(up, down);
 53     up = sign * (up / g);
 54     down = down / g;
 55 }
 56 
 57 // 求最大公约数
 58 int Fraction::gcd(int a, int b) {
 59     return b == 0 ? a : gcd(b, a % b);
 60 }
 61 
 62 // 输出分数
 63 void output(const Fraction& frac) {
 64     if (frac.down == 1) {
 65         std::cout << frac.up;
 66     } else {
 67         std::cout << frac.up << "/" << frac.down;
 68     }
 69 }
 70 
 71 // 分数相加
 72 Fraction add(const Fraction& f1, const Fraction& f2) {
 73     int up = f1.up * f2.down + f2.up * f1.down;
 74     int down = f1.down * f2.down;
 75     Fraction result(up, down);
 76     result.simplify();
 77     return result;
 78 }
 79 
 80 // 分数相减
 81 Fraction sub(const Fraction& f1, const Fraction& f2) {
 82     int up = f1.up * f2.down - f2.up * f1.down;
 83     int down = f1.down * f2.down;
 84     Fraction result(up, down);
 85     result.simplify();
 86     return result;
 87 }
 88 
 89 // 分数相乘
 90 Fraction mul(const Fraction& f1, const Fraction& f2) {
 91     int up = f1.up * f2.up;
 92     int down = f1.down * f2.down;
 93     Fraction result(up, down);
 94     result.simplify();
 95     return result;
 96 }
 97 
 98 // 分数相除
 99 Fraction div(const Fraction& f1, const Fraction& f2) {
100     if (f2.up == 0) {
101         std::cerr << "分母不能为0" << std::endl;
102         return Fraction(0, 1);
103     }
104     int up = f1.up * f2.down;
105     int down = f1.down * f2.up;
106     Fraction result(up, down);
107     result.simplify();
108     return result;
109 }

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

##运行结果

image

 ##问题回答

我选择的是友元函数,理由:友元函数可以直接访问分子分母这些私有成员,无需通过类的接口间接获取;静态成员函数需要通过类名或对象来调用,而不能直接访问私有成员;命名空间方案的自由函数也无法直接访问类的私有成员,必须通过类提供的公有接口来获取分子分母;       综上,友元函数较为适合。

 

posted @ 2025-10-28 19:15  xzhls  阅读(7)  评论(0)    收藏  举报