实验二

实验任务一

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();
37     
38  

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 } 

 

task2.1.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 091436

 

问题1

不能屏幕截图 2025-10-27 221745

在 C++ 中,友元函数的声明只是表明该函数是类的友元,可以访问类的私有成员,但友元函数本身并不是类的成员函数。如果在类外部去掉对  func  函数的声明  void func(); ,那么当程序中其他地方调用  func  函数时,编译器无法找到  func  函数的声明,会报“未定义的标识符”之类的错误,因为编译器不知道  func  函数的存在,无法进行正确的编译链接。

问题2

普通构造函数  T(int x = 0, int y = 0); 

功能:用于创建  T  类的对象,在创建对象时初始化对象的成员变量。可以接受 0、1 或 2 个参数,若不传入参数则使用默认值 0 初始化  x  和  y 
调用时机:当用以下方式创建对象时调用:

 T t1; (无参,使用默认值初始化)

T t2(5); (单参, x = 5 , y  使用默认值 0)
T t3(3, 4); (双参, x = 3 , y = 4 )

复制构造函数  T(const T &t); 

功能:用一个已存在的  T  类对象  t  来初始化一个新的  T  类对象,实现对象的“深拷贝”(若有动态内存等需要深拷贝的成员时,需在复制构造函数中处理,这里假设是普通成员)。
调用时机:
用一个已有的  T  类对象初始化另一个新对象时,如  T t4 = t3; 
当函数以值传递的方式传递  T  类对象参数时
 当函数返回  T  类对象(值返回)时

移动构造函数  T(T &&t); 
功能:利用右值引用,将一个临时的、即将被销毁的  T  类对象(右值)的资源“移动”到新创建的对象中,避免不必要的拷贝,提高性能。
调用时机:当用右值(如临时对象、 std::move  转换后的对象)初始化新的  T  类对象时,例如  T t5 = std::move(t4); 。
析构函数  ~T(); 
功能:在  T  类对象的生命周期结束时,执行清理工作,如释放对象所占用的动态内存、关闭文件等资源(若有相关资源需要释放)。
调用时机:当  T  类对象的作用域结束(如局部对象离开其定义的代码块),或者动态创建的对象被  delete  时,析构函数会被自动调用。

问题3

不能

屏幕截图 2025-10-27 222018

 

类的静态成员变量的定义(即分配内存并初始化)应该放在  .cpp  文件中。如果将  T.cpp  中  line13 - 15 (静态成员  doc 、 max_cnt 、 cnt  的定义)剪切到  T.h  的末尾,当多个源文件包含  T.h  时,会导致这些静态成员被多次定义,违反了 C++ 的“单定义规则(ODR)”,编译器会报“多重定义”的错误,因为头文件会被多个源文件包含,从而导致静态成员的定义重复

实验任务二

Complex.h
 1 #ifndef COMPLEX_H  // 头文件保护宏:防止头文件被重复包含
 2 #define COMPLEX_H
 3 #include <string>   // 引入string类型的头文件(因为要定义doc属性)
 4 #include <iostream> // 引入输入输出头文件(因为要输出复数)
 5 using namespace std; // 使用std命名空间,简化代码(避免写std::string、std::cout)
 6 class Complex {  // 定义Complex类
 7 public:
 8     //类属性:公有静态常量doc
 9     static const string doc;  
10     //static:表示这是“类的属性”(所有Complex对象共享,不需要创建对象就能访问)
11     //const:表示这个属性的值不能被修改
12     //作用:存储类的说明信息(实验要求的“类属性”)
13     //构造函数声明(用于创建对象)
14     Complex(double real = 0.0, double imag = 0.0);  // 普通构造函数
15     //形参带默认值:
16     //无参调用(Complex c1;):real=0.0、imag=0.0 → 构造0+0i
17     //单参调用(Complex c2(3.5);):real=3.5、imag=0.0 → 构造3.5+0i
18     //双参调用(Complex c3(3, -4);):real=3、imag=-4 → 构造3-4i
19     Complex(const Complex& other);  // 复制构造函数
20     //形参是“const Complex&”:表示传入一个已存在的Complex对象的“只读引用”
21     //作用:用已有的对象构造新对象(比如Complex c4(c2); 或 Complex c5 = c2;)
22     //接口方法声明(类的“功能函数”)
23     double get_real() const;  // 返回实部
24     double get_imag() const;  // 返回虚部
25     //const:表示这个函数不会修改对象的成员变量(只读操作)
26     void add(const Complex& other);  // 自身累加另一个复数
27     //作用:把other的实部/虚部加到当前对象上(比如c1.add(c2) → c1 = c1 + c2)
28     //友元函数声明(友元可以直接访问类的私有成员)
29     friend void output(const Complex& c);          // 输出复数(a+bi格式)
30     friend double abs(const Complex& c);           // 复数取模
31     friend Complex add(const Complex& c1, const Complex& c2);  // 两个复数相加
32     friend bool is_equal(const Complex& c1, const Complex& c2); // 判断复数相等
33     friend bool is_not_equal(const Complex& c1, const Complex& c2); // 判断不相等
34     //friend:表示这些函数不是类的成员,但可以直接访问Complex的私有成员(real、imag)
35  private:  //私有成员:只有类内部和友元能访问
36     double real;  //存储复数的实部
37     double imag;  //存储复数的虚部
38 };
39 #endif  //结束头文件保护宏

 

Complex.cpp
 1 #include "Complex.h"  // 包含头文件,让编译器知道Complex类的结构
 2 #include <cmath>      // 引入数学头文件(因为要计算平方根sqrt,用于取模)
 3 //初始化类的静态常量doc
 4 const string Complex::doc = "a simplified complex class";
 5 //静态成员必须在“类外”初始化(因为它是“类的属性”,不是对象的属性)
 6 //这里给doc赋值为实验要求的说明信息
 7 //普通构造函数的实现
 8 Complex::Complex(double real, double imag) : real(real), imag(imag) {}
 9 //Complex:::表示这是Complex类的成员函数
10 //real(real), imag(imag):初始化列表(高效初始化成员变量)
11 //把形参real的值赋给类的私有成员real
12 //把形参imag的值赋给类的私有成员imag
13 //复制构造函数的实现
14 Complex::Complex(const Complex& other) : real(other.real), imag(other.imag) {}
15 //other是传入的已有对象
16 //把other的real和imag的值,赋给新对象的real和imag
17 //作用:保证新对象和原对象的内容完全一致
18 //get_real()的实现:返回实部
19 double Complex::get_real() const {
20     return real;  // 直接返回私有成员real
21 }
22 //get_imag()的实现:返回虚部
23 double Complex::get_imag() const {
24     return imag;  // 直接返回私有成员imag
25 }
26 //add()的实现:自身累加另一个复数
27  void Complex::add(const Complex& other) {
28     this->real += other.real;  // 当前对象的real = 当前real + other的real
29     this->imag += other.imag;  // 当前对象的imag = 当前imag + other的imag
30     //this:指向当前对象的指针(表示“自己”)
31 }
32  //友元函数output()的实现:输出复数(a+bi格式)
33  void output(const Complex& c) {
34     cout << c.real;  // 先输出实部
35     if (c.imag >= 0) {  // 如果虚部是正数,输出“+ 虚部i”
36         cout << " + " << c.imag << "i";
37     } else {  // 如果虚部是负数,输出“- 绝对值i”(比如imag=-4 → 输出“- 4i”)
38         cout << " - " << -c.imag << "i";
39     }
40 }
41  //友元函数abs()的实现:计算复数的模
42  double abs(const Complex& c) {
43     // 复数的模公式:√(实部2 + 虚部2)
44     return sqrt(c.real * c.real + c.imag * c.imag);
45 }
46  //友元函数add()的实现:两个复数相加,返回新的复数
47  Complex add(const Complex& c1, const Complex& c2) {
48     // 新复数的实部 = c1实部 + c2实部
49     // 新复数的虚部 = c1虚部 + c2虚部
50     return Complex(c1.real + c2.real, c1.imag + c2.imag);
51 }
52  //友元函数is_equal()的实现:判断两个复数是否相等
53  bool is_equal(const Complex& c1, const Complex& c2) {
54     // 复数相等的条件:实部相等 且 虚部相等
55     return (c1.real == c2.real) && (c1.imag == c2.imag);
56 }
57  // 11. 友元函数is_not_equal()的实现:判断两个复数是否不相等
58  bool is_not_equal(const Complex& c1, const Complex& c2) {
59     // 直接复用is_equal的结果,取反即可
60     return !is_equal(c1, c2);
61 }

 

task2.2.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-27 225037

 

问题1

使用形式简洁性:标准库模板类  std::complex  更简洁。从表格中可以看到,自定义类需要通过函数名(如  add 、 is_equal )来进行运算和比较,而标准库类可以直接使用熟悉的运算符( += 、 + 、 == 、 != )以及流操作( cout << ),更符合 C++ 常规的编程习惯,书写更简洁直观。
函数和运算内在关联:有内在关联。标准库  std::complex  通过运算符重载等方式,将复数的运算(加、减、乘、除等)和比较等操作与对应的运算符关联起来,使得使用方式和内置类型(如  int 、 double )类似,而自定义类需要自己定义函数来模拟这些操作,本质上都是为了实现复数的各种数学运算和功能,只是标准库的实现更贴合语言的原生语法。

问题2
2 - 1:是。因为  output  需要访问复数的实部和虚部来进行输出; abs  需要根据实部和虚部计算复数的模; add  需要访问两个复数的实部和虚部来进行加法运算,所以它们都需要访问私有数据  real  和  imag ,将其设为友元是合理的。
2 - 2:标准库  std::complex  中, abs  不是  std::complex  类的友元。 std::abs  是一个非成员函数(通过函数重载来支持  std::complex  类型),它可以通过  std::complex  类的公有接口(如  real()  和  imag()  成员函数)来获取实部和虚部,进而计算模,不需要成为友元。

2 - 3:当一个函数需要访问类的私有成员,且这个函数不适合作为类的成员函数(比如运算符重载的非成员函数、一些工具函数等)时,考虑使用  friend 。例如,双目运算符(如  + ,两个操作数类型相同或不同)如果要支持更灵活的操作数顺序,作为非成员函数实现时,若需要访问类的私有成员,就需要声明为友元;还有一些外部工具函数,需要操作类的内部私有数据来完成特定功能,也可以声明为友元。

问题3
如果要禁用  Complex c4 = c2;  这种拷贝初始化形式(即禁用复制构造函数),可以将复制构造函数声明为私有,或者使用  = delete  来显式删除复制构造函数。

实验任务三

PlayerControl.h
 1 #pragma once  // 头文件保护(等价于#ifndef...#define...#endif)
 2 #include <string>
 3  // 枚举类型:表示播放控制指令
 4  enum class ControlType { Play, Pause, Next, Prev, Stop, Unknown };
 5  class PlayerControl {
 6  public:
 7     // 构造函数
 8     PlayerControl();
 9     // 接口1:将用户输入的字符串(如"play")转换为枚举值
10     ControlType parse(const std::string& control_str);
11     // 接口2:执行控制指令(模拟播放行为)
12     void execute(ControlType cmd) const;
13     // 类方法:获取操作总次数
14     static int get_cnt();
15  private:
16     // 类属性:静态变量,记录所有对象的操作总次数
17     static int total_cnt;
18  };

 

PlayerControl.cpp
 1 #include "PlayerControl.h"
 2 #include <iostream>
 3 #include <algorithm>  // 用于字符串大小写转换
 4 #include <cctype>     // 用于字符大小写判断
 5 // 初始化静态成员:操作总次数初始为0
 6 int PlayerControl::total_cnt = 0;
 7 // 构造函数:无额外逻辑,仅初始化对象
 8 PlayerControl::PlayerControl() {}
 9 // 接口1:字符串转枚举值(忽略大小写)
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     // 步骤2:根据小写字符串匹配枚举值
16     if (lower_str == "play") {
17         total_cnt++;  // 操作次数+1
18         return ControlType::Play;
19     } else if (lower_str == "pause") {
20         total_cnt++;
21         return ControlType::Pause;
22     } else if (lower_str == "next") {
23         total_cnt++;
24         return ControlType::Next;
25     } else if (lower_str == "prev") {
26         total_cnt++;
27         return ControlType::Prev;
28     } else if (lower_str == "stop") {
29         total_cnt++;
30         return ControlType::Stop;
31     } else {
32         // 未知指令
33         return ControlType::Unknown;
34     }
35 }
36 // 接口2:执行控制指令(模拟输出)
37 void PlayerControl::execute(ControlType cmd) const {
38     // 根据枚举值输出对应的控制行为
39     switch (cmd) {
40         case ControlType::Play:
41             std::cout << "[Play] 播放音乐..." << std::endl;
42             break;
43         case ControlType::Pause:
44             std::cout << "[Pause] 音乐已暂停" << std::endl;
45             break;
46         case ControlType::Next:
47             std::cout << "[Next] 切换到下一首" << std::endl;
48             break;
49         case ControlType::Prev:
50             std::cout << "[Prev] 回到上一首" << std::endl;
51             break;
52         case ControlType::Stop:
53             std::cout << "[Stop] 音乐已停止" << std::endl;
54             break;
55         default:
56             std::cout << "[Error] 未知控制指令" << std::endl;
57             break;
58     }
59 }
60 // 类方法:返回操作总次数
61 int PlayerControl::get_cnt() {
62     return total_cnt;
63  }

 

task2.3.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") {   // 输入quit则退出
 9             break;
10         }
11         // 步骤1:将用户输入的字符串转为枚举指令
12         ControlType cmd = controller.parse(control_str);
13         // 步骤2:执行指令
14         controller.execute(cmd);
15         // 步骤3:输出当前操作总次数
16         std::cout << "Current Player control: " << PlayerControl::get_cnt() << "\n\n";
17     }
18 }
19 int main() {
20     test();  // 运行测试
21     return 0;
22 }

运行结果

屏幕截图 2025-10-27 231408

 

实验任务四

Fraction.h
 1 #pragma once  // 头文件保护:防止同一文件被重复包含(等价于#ifndef+#define+#endif)
 2 #include <string>  // 引入string类型的头文件(因为要定义类属性doc)
 3 using namespace std;  // 使用std命名空间,简化代码(避免写std::string)
 4 class Fraction {  // 定义分数类Fraction
 5 public:
 6     // 类属性:公有静态常量,用于类说明
 7     static const string doc;  // static表示“类的属性”(所有对象共享),const表示不可修改
 8     // 构造函数声明
 9     Fraction(int up = 0, int down = 1);  // 普通构造:默认分子0、分母1(支持无参/单参/双参构造)
10     Fraction(const Fraction& other);     // 复制构造:用已有对象构造新对象
11     // 接口方法声明(类的功能函数)
12     int get_up() const;  // 返回分子,const表示函数不修改对象成员
13     int get_down() const;  // 返回分母,const表示函数不修改对象成员
14     Fraction negative() const;  // 求负:返回新分数对象,原对象不变
15     // 友元工具函数声明(友元可直接访问类的私有成员)
16     friend void output(const Fraction& f);  // 输出分数
17     friend Fraction add(const Fraction& f1, const Fraction& f2);  // 分数相加
18     friend Fraction sub(const Fraction& f1, const Fraction& f2);  // 分数相减
19     friend Fraction mul(const Fraction& f1, const Fraction& f2);  // 分数相乘
20     friend Fraction div(const Fraction& f1, const Fraction& f2);  // 分数相除
21 private:  // 私有成员:仅类内部和友元能访问
22     int up;    // 存储分数的分子
23     int down;  // 存储分数的分母
24     void reduce();  // 内部工具函数:分数化简(约分)
25     int gcd(int a, int b) const;  // 内部工具函数:求最大公约数(用于约分)
26 };

 

Fraction.cpp
 1 #include "Fraction.h"  // 包含头文件,让编译器知道Fraction类的结构
 2 #include <iostream>    // 引入输入输出头文件(用于输出错误信息)
 3 #include <cstdlib>     // 引入stdlib头文件(用于abs()函数,求绝对值)
 4 // 初始化类的静态常量doc(静态成员必须在类外初始化)
 5 const string Fraction::doc = "Fraction类v0.01版.\n目前仅支持分数对象的构造、输出、加减乘除运算";
 6 // 普通构造函数:初始化分子、分母,并处理异常、化简分数
 7 Fraction::Fraction(int up, int down) : up(up), down(down) {
 8     // 处理分母为0的错误:直接终止程序并提示
 9     if (down == 0) {
10         cerr << "错误:分母不能为0!" << endl;  // cerr:输出错误信息
11         exit(1);  // 终止程序(返回1表示异常退出)
12     }
13     // 确保分母为正:若分母是负数,将符号转移到分子
14     if (down < 0) {
15         up = -up;    // 分子取反
16         down = -down;  // 分母取反(转为正数)
17     }
18     reduce();  // 调用内部工具函数,化简分数(约分)
19 }
20 // 复制构造函数:用已有对象other构造新对象
21 Fraction::Fraction(const Fraction& other) : up(other.up), down(other.down) {}
22 //other是已有对象的“只读引用”
23 //用other的up和down初始化新对象的up和down
24 // 返回分子(接口方法)
25 int Fraction::get_up() const {
26     return up;  // 直接返回私有成员up
27 }
28 // 返回分母(接口方法)
29 int Fraction::get_down() const {
30     return down;  // 直接返回私有成员down
31 }
32 // 求负:返回新的分数对象(原对象不变)
33 Fraction Fraction::negative() const {
34     return Fraction(-up, down);  // 构造新分数,分子取反、分母不变
35 }
36 // 内部工具函数:求a和b的最大公约数(用于约分)
37 int Fraction::gcd(int a, int b) const {
38     a = abs(a);  // 转为绝对值(避免负数影响计算)
39     b = abs(b);
40     while (b != 0) {  // 辗转相除法求最大公约数
41         int temp = b;
42         b = a % b;
43         a = temp;
44     }
45     return a;  // a是最大公约数
46 }
47 // 内部工具函数:分数化简(约分)
48 void Fraction::reduce() {
49     int common = gcd(up, down);  // 求分子和分母的最大公约数
50     up /= common;    // 分子除以最大公约数
51     down /= common;  // 分母除以最大公约数
52 }
53 // 友元函数:输出分数(化简后的格式)
54 void output(const Fraction& f) {
55     if (f.down == 1) {  // 若分母是1,直接输出分子(如2/1 → 2)
56         cout << f.up;
57     } else {  // 否则输出“分子/分母”格式(如-2/3)
58         cout << f.up << "/" << f.down;
59     }
60 }
61 // 友元函数:分数相加
62 Fraction add(const Fraction& f1, const Fraction& f2) {
63     // 分数加法公式:f1 + f2 = (f1.up*f2.down + f2.up*f1.down) / (f1.down*f2.down)
64     int new_up = f1.up * f2.down + f2.up * f1.down;  // 新分子
65     int new_down = f1.down * f2.down;  // 新分母
66     return Fraction(new_up, new_down);  // 构造新分数(自动化简)
67 }
68 // 友元函数:分数相减
69 Fraction sub(const Fraction& f1, const Fraction& f2) {
70     // 分数减法公式:f1 - f2 = (f1.up*f2.down - f2.up*f1.down) / (f1.down*f2.down)
71     int new_up = f1.up * f2.down - f2.up * f1.down;
72     int new_down = f1.down * f2.down;
73     return Fraction(new_up, new_down);
74 }
75 // 友元函数:分数相乘
76 Fraction mul(const Fraction& f1, const Fraction& f2) {
77     // 分数乘法公式:f1 * f2 = (f1.up*f2.up) / (f1.down*f2.down)
78     int new_up = f1.up * f2.up;
79     int new_down = f1.down * f2.down;
80     return Fraction(new_up, new_down);
81 }
82 // 友元函数:分数相除
83 Fraction div(const Fraction& f1, const Fraction& f2) {
84     // 分数除法公式:f1 / f2 = (f1.up*f2.down) / (f1.down*f2.up)(等价于乘以f2的倒数)
85     int new_up = f1.up * f2.down;
86     int new_down = f1.down * f2.up;
87     return Fraction(new_up, new_down);
88 }

 

task2.4.cpp
 1 #include "Fraction.h"  // 包含Fraction类的头文件
 2 #include <iostream>     // 引入输入输出头文件
 3 void test1();  // 声明测试函数1(基础功能测试)
 4 void test2();  // 声明测试函数2(分母为0测试)
 5 int main() {  // 程序入口
 6     std::cout << "测试1:Fraction类基础功能测试\n";  // 输出测试标题
 7     test1();  // 调用测试函数1
 8     std::cout << "\n测试2:分母为0测试:\n";  // 输出测试标题
 9     test2();  // 调用测试函数2
10 }
11 void test1() {  // 测试函数1:基础功能
12     using std::cout;  // 简化cout的写法(避免写std::cout)
13     using std::endl;  // 简化endl的写法
14     cout << "Fraction类测试:" << endl;
15     cout << Fraction::doc << endl << endl;  // 输出类的说明信息
16     // 构造分数对象
17     Fraction f1(5);  // 单参构造:分子5,分母默认1 → 5/1
18     Fraction f2(3, -4), f3(-18, 12);  // f2:3/-4→-3/4;f3:-18/12→-3/2
19     Fraction f4(f3);  // 复制构造:f4和f3相同→-3/2
20     // 输出各个分数
21     cout << "f1 = "; output(f1); cout << endl;  // 输出f1:5
22     cout << "f2 = "; output(f2); cout << endl;  // 输出f2:-3/4
23     cout << "f3 = "; output(f3); cout << endl;  // 输出f3:-3/2
24     cout << "f4 = "; output(f4); cout << endl;  // 输出f4:-3/2
25     // 测试求负功能
26     const Fraction f5(f4.negative());  // f4求负→3/2
27     cout << "f5 = "; output(f5); cout << endl;  // 输出f5:3/2
28     // 测试get_up/get_down
29     cout << "f5.get_up() = " << f5.get_up()
30         << ", f5.get_down() = " << f5.get_down() << endl;  // 输出3和2
31     // 测试分数运算
32     cout << "f1 + f2 = "; output(add(f1, f2)); cout << endl;  // 5 + (-3/4) = 17/4
33     cout << "f1 - f2 = "; output(sub(f1, f2)); cout << endl;  // 5 - (-3/4) = 23/4
34     cout << "f1 * f2 = "; output(mul(f1, f2)); cout << endl;  // 5 * (-3/4) = -15/4
35     cout << "f1 / f2 = "; output(div(f1, f2)); cout << endl;  // 5 / (-3/4) = -20/3
36     cout << "f4 + f5 = "; output(add(f4, f5)); cout << endl;  // (-3/2) + 3/2 = 0
37 }
38 void test2() {  // 测试函数2:分母为0的情况
39     using std::cout;
40     using std::endl;
41     Fraction f6(42, 55), f7(0, 3);  // f7:0/3→0/1
42     cout << "f6 = "; output(f6); cout << endl;  // 输出f6:42/55
43     cout << "f7 = "; output(f7); cout << endl;  // 输出f7:0
44     cout << "f6 / f7 = "; 
45     // f6/f7 → 42/55 ÷ 0 → 分母为0,触发构造函数的错误提示
46     output(div(f6, f7)); cout << endl;
47 }

 

运行结果
屏幕截图 2025-10-27 232800

问题

选择友元函数方案来实现  output 、 add 、 sub 、 mul 、 div 。
决策理由
友元方案的优缺点
优点:
友元函数可以直接访问类的私有成员(如分子  numerator  和分母  denominator ),在实现分数的输出和运算时,无需通过类的公有接口间接获取数据,代码实现更加简洁高效。例如在  add  函数中,能直接使用  frac1.numerator 、 frac1.denominator  等进行计算,不需要调用  getNumerator  和  getDenominator  方法。
对于二元操作(如两个分数相加、相减等),友元函数的参数传递方式更灵活,可以自然地处理两个操作数的关系,语法上也更接近普通的数学运算表达式。
缺点:
友元函数破坏了类的封装性,因为它可以直接访问类的私有成员,使得类的内部实现对友元函数可见,降低了类的封装程度。
友元函数的数量过多时,会使得类的接口不够清晰,难以维护和管理。
静态成员函数方案的适用场景
静态成员函数属于类本身,而不是类的实例。适用于操作与类的所有实例相关的静态数据成员,或者执行的操作不需要访问特定实例的私有成员(只需要类级别的信息)的场景。例如,统计类的对象个数的函数,或者根据类的一些静态配置信息进行计算的函数。但对于分数的输出和运算,每个操作都需要针对具体的分数实例(访问实例的分子和分母),所以不适合用静态成员函数。
命名空间方案的考虑因素
命名空间主要用于组织代码,避免命名冲突。如果有多个与分数相关的函数,将它们放在同一个命名空间(如  namespace FractionOps )中,可以使代码的逻辑更加清晰,便于管理。但命名空间本身并不能解决函数访问类私有成员的问题,如果使用命名空间中的普通自由函数,仍然需要通过类的公有接口来访问私有成员,会增加代码的复杂度和开销。而友元函数可以在使用命名空间的同时,直接访问类的私有成员,结合了命名空间的组织性和友元函数的便利性。在本题中,虽然也可以使用命名空间,但友元函数能更直接地实现功能,所以优先选择友元。

posted @ 2025-10-27 23:56  stezin-  阅读(5)  评论(0)    收藏  举报