实验二

一、实验内容

任务一:

 

代码组织:

 

  T.h 内容:类T的声明、友元函数声明

 

  T.cpp 内容:类T的实现、友元函数实现

 

  task1.cpp 内容:测试模块、main函数

 

头文件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 // static成员数据类外初始化
 7 const std::string T::doc{"a simple class sample"};
 8 const int T::max_cnt = 999;
 9 int T::cnt = 0;
10 
11 // 类方法
12 int T::get_cnt() 
13 {
14    return cnt;
15 }
16 
17 // 对象方法
18 T::T(int x, int y): m1{x}, m2{y} 
19 { 
20     ++cnt; 
21     std::cout << "T constructor called.\n";
22 } 
23 
24 T::T(const T &t): m1{t.m1}, m2{t.m2} 
25 {
26     ++cnt;
27     std::cout << "T copy constructor called.\n";
28 }
29 
30 T::T(T &&t): m1{t.m1}, m2{t.m2} 
31 {
32     ++cnt;
33     std::cout << "T move constructor called.\n";
34 }    
35 
36 T::~T() 
37 {
38     --cnt;
39     std::cout << "T destructor called.\n";
40 }           
41 
42 void T::adjust(int ratio)
43  {
44     m1 *= ratio;
45     m2 *= ratio;
46 }    
47 
48 void T::display() const 
49 {
50     std::cout << "(" << m1 << ", " << m2 << ")" ;
51 }     
52 
53 // 普通函数实现
54 void func() 
55 {
56     T t5(42);
57     t5.m2 = 2049;
58     std::cout << "t5 = "; t5.display(); std::cout << '\n';
59 }

源代码task1.cpp

 1 #include "T.h"
 2 #include <iostream>
 3 
 4 void test_T();
 5 
 6 int main() 
 7 {
 8     std::cout << "test Class T: \n";
 9     test_T();
10 
11     std::cout << "\ntest friend func: \n";
12     func();
13 }
14 
15 void test_T() 
16 {
17      using namespace std; 
18 
19     cout << "T info: " << T::doc << endl;
20     cout << "T objects'max count: " << T::max_cnt << endl;
21     cout << "T objects'current count: " << T::get_cnt() << endl << endl;
22 
23     T t1;
24     cout << "t1 = "; t1.display(); cout << endl;
25 
26     T t2(3, 4);
27     cout << "t2 = "; t2.display(); cout << endl;
28 
29     T t3(t2);
30     t3.adjust(2);
31     cout << "t3 = "; t3.display(); cout << endl;
32 
33     T t4(std::move(t2));
34     cout << "t4 = "; t4.display(); cout << endl;
35 
36     cout << "test: T objects'current count: " << T::get_cnt() << endl;
37 }

运行结果图:

image

 观察与思考:

问题1:

T.h中,在类T内部,已声明func是T的友元函数。在类外部,去掉line36,重新编译,程序能否正常运行。

如果能,回答YES;如果不能,以截图形式提供编译报错信息,说明原因。

  不能,截图如下,原因是类内部声明友元函数func后,若类外部不进行函数声明,编译器无法识别func的定义(若存在)或调用,会因 “未声明的标识符” 报错。

image

问题2:

T.h中,line9-12给出了各种构造函数、析构函数。总结它们各自的功能、调用时机。

函数 功能 调用时机
普通构造函数 初始化类的对象,为对象的成员变量分配内存并赋予初始值 创建类的对象时调用
复制构造函数 用已存在的同类型对象初始化新对象 用对象初始化新对象时、函数按值传递类对象参数时、函数返回类对象(非引用)时
移动构造函数 利用临时对象的资源初始化新对象,避免不必要的拷贝,提高性能 当有右值引用的类对象作为初始化源时(如返回临时对象、用std::move转换的对象初始化新对象)
析构函数 释放对象占用的资源(如动态分配的内存),完成对象销毁前的清理工作 对象生命周期结束时自动调用

 

 

 

 

 

 

 

 问题3:

T.cpp中,line13-15,剪切到T.h的末尾,重新编译,程序能否正确编译。

如不能,以截图形式给出报错信息,分析原因。

不能,截图如下。原因是类的静态成员初始化代码属于类外定义,若剪切到头文件(.h)末尾,会导致重复定义(因为头文件可能被多个源文件包含)。静态成员的类外初始化应放在.cpp文件中,保证只定义一次。

image

任务二:

Complex.h

 

 1 #ifndef COMPLEX_H
 2 #define COMPLEX_H
 3 
 4 #include <string>
 5 class Complex{
 6     public:
 7         static const std::string doc;
 8         
 9         Complex(double r=0.0,double i=0.0);
10         Complex(const Complex& other);
11         
12         double get_real() const;
13         double get_imag() const;
14         
15         void add(const Complex& other);
16         
17         friend void output(const Complex &c);
18         friend double abs(const Complex& c);
19         
20         friend Complex add(const Complex& c1,const Complex& c2);
21         
22         friend bool isequal(const Complex& c1,const Complex& c2);
23         friend bool is_not_equal(const Complex& c1,const Complex& c2);
24         
25     private:
26         double real,imag;
27 };
28 
29 void output(const Complex &c);
30 double abs(const Complex& c);
31 
32 Complex add(const Complex& c1,const Complex& c2);
33 
34 bool isequal(const Complex& c1,const Complex& c2);
35 bool is_not_equal(const Complex& c1,const Complex& c2);
36 
37 #endif

Complex.cpp

 

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

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 : " << isequal(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 }

运行测试结果截图:

image

  观察与思考:

问题1:

比较自定义类Complex和标准库模板类complex的用法,在使用形式上,哪一种更简洁?函数和运算内在有关联吗?

  简洁性:标准库模板类complex更简洁。它通过运算符重载(如+=+==等)实现操作,形式更贴近自然数学表达式,符合程序员的使用习惯。

  函数和运算的内在关联:标准库的运算符本质是函数的重载,功能一致,只是表现形式不同。

问题2:

2-1:自定义Complex中, output/abs/add/ 等均设为友元,它们真的需要访问 私有数据 吗?(回答“是/否”并给出理由)

  是。因为output需要访问复数的实部和虚部来输出,abs需要根据实部和虚部计算模长,add需要访问两个复数的实部和虚部来做加法,这些操作都依赖类的私有数据,所以需要设为友元。

 

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

  否。标准库std::complexabs函数是通过公有接口(如real()imag()成员函数)获取实部和虚部来计算的,未将其设为友元。

2-3:什么时候才考虑使用 friend?总结你的思考。

  当函数需要直接访问类的私有成员,且无法通过类的公有接口间接实现时;或者两个类需要互相访问对方的私有成员时,才考虑使用friend

问题3:

如果构造对象时禁用=形式,即遇到Complex c4 = c2;编译报错,类Complex的设计应如何调整?

  将复制构造函数声明为explicit,即explicit Complex(const Complex& other);

任务三:

PlayerControl.h

 

 1 #pragma once
 2 #include <string>
 3 
 4 enum class ControlType {Play, Pause, Next, Prev, Stop, Unknown};
 5 
 6 class PlayerControl {
 7 public:
 8     PlayerControl();
 9 
10     ControlType parse(const std::string& control_str);   // 实现std::string --> ControlType转换
11     void execute(ControlType cmd) const;   // 执行控制操作(以打印输出模拟)       
12 
13     static int get_cnt();
14 
15 private:
16     static int total_cnt;   
17 };

 

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     std::string lower_str = control_str;
11     std::transform(lower_str.begin(), lower_str.end(), lower_str.begin(), 
12                    [](unsigned char c) { return std::tolower(c); });
13     ControlType result = ControlType::Unknown;
14     
15     if (lower_str == "play") {
16         result = ControlType::Play;
17     } else if (lower_str == "pause") {
18         result = ControlType::Pause;
19     } else if (lower_str == "next") {
20         result = ControlType::Next;
21     } else if (lower_str == "prev") {
22         result = ControlType::Prev;
23     } else if (lower_str == "stop") {
24         result = ControlType::Stop;
25     } else {
26         result = ControlType::Unknown;
27     }
28     total_cnt++;
29     return result;
30 }
31 
32 void PlayerControl::execute(ControlType cmd) const {
33     switch (cmd) {
34     case ControlType::Play:  std::cout << "[play] Playing music...\n"; break;
35     case ControlType::Pause: std::cout << "[Pause] Music paused\n";    break;
36     case ControlType::Next:  std::cout << "[Next] Skipping to next track\n"; break;
37     case ControlType::Prev:  std::cout << "[Prev] Back to previous track\n"; break;
38     case ControlType::Stop:  std::cout << "[Stop] Music stopped\n"; break;
39     default:                 std::cout << "[Error] unknown control\n"; break;
40     }
41 }
42 
43 int PlayerControl::get_cnt() {
44     return total_cnt;
45 }

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 }

运行结果截图:

 

image

任务四:

Fraction.h

 1 #pragma once
 2 #include <string>
 3 
 4 class Fraction {
 5 public:
 6     Fraction(int up = 0, int down = 1);
 7     Fraction(const Fraction& f);
 8 
 9     int get_up() const;
10     int get_down() const;
11     Fraction negative() const;
12 
13     static const std::string doc;
14 
15 private:
16     int up, down;
17     void simplify();
18 
19     friend void output(const Fraction& f);
20     friend Fraction add(const Fraction& a, const Fraction& b);
21     friend Fraction sub(const Fraction& a, const Fraction& b);
22     friend Fraction mul(const Fraction& a, const Fraction& b);
23     friend Fraction div(const Fraction& a, const Fraction& b);
24 };
 1 #include "Fraction.h"
 2 #include <iostream>
 3 #include <numeric>
 4 #include <stdexcept>
 5 
 6 const std::string Fraction::doc = "Fraction类 v0.01版";
 7 
 8 Fraction::Fraction(int u, int d): up{u}, down{d} {
 9     if (down == 0) throw std::invalid_argument("Denominator cannot be zero");
10     simplify();
11 }
12 
13 Fraction::Fraction(const Fraction& f): up{f.up}, down{f.down} {}
14 
15 void Fraction::simplify() {
16     if (down < 0) { down = -down; up = -up; }
17     int g = std::gcd(up, down);
18     if (g != 0) { up /= g; down /= g; }
19 }
20 
21 int Fraction::get_up() const { return up; }
22 int Fraction::get_down() const { return down; }
23 
24 Fraction Fraction::negative() const {
25     return Fraction(-up, down);
26 }
27 
28 void output(const Fraction& f) {
29     std::cout << f.up << "/" << f.down;
30 }
31 
32 Fraction add(const Fraction& a, const Fraction& b) {
33     return Fraction(a.up * b.down + b.up * a.down, a.down * b.down);
34 }
35 
36 Fraction sub(const Fraction& a, const Fraction& b) {
37     return Fraction(a.up * b.down - b.up * a.down, a.down * b.down);
38 }
39 
40 Fraction mul(const Fraction& a, const Fraction& b) {
41     return Fraction(a.up * b.up, a.down * b.down);
42 }
43 
44 Fraction div(const Fraction& a, const Fraction& b) {
45     if (b.up == 0) throw std::invalid_argument("Division by zero");
46     return Fraction(a.up * b.down, a.down * b.up);
47 }
 1 #include "Fraction.h"
 2 #include <iostream>
 3 #include <numeric>
 4 #include <stdexcept>
 5 
 6 const std::string Fraction::doc = "Fraction类 v0.01版";
 7 
 8 Fraction::Fraction(int u, int d): up{u}, down{d} {
 9     if (down == 0) throw std::invalid_argument("Denominator cannot be zero");
10     simplify();
11 }
12 
13 Fraction::Fraction(const Fraction& f): up{f.up}, down{f.down} {}
14 
15 void Fraction::simplify() {
16     if (down < 0) { down = -down; up = -up; }
17     int g = std::gcd(up, down);
18     if (g != 0) { up /= g; down /= g; }
19 }
20 
21 int Fraction::get_up() const { return up; }
22 int Fraction::get_down() const { return down; }
23 
24 Fraction Fraction::negative() const {
25     return Fraction(-up, down);
26 }
27 
28 void output(const Fraction& f) {
29     std::cout << f.up << "/" << f.down;
30 }
31 
32 Fraction add(const Fraction& a, const Fraction& b) {
33     return Fraction(a.up * b.down + b.up * a.down, a.down * b.down);
34 }
35 
36 Fraction sub(const Fraction& a, const Fraction& b) {
37     return Fraction(a.up * b.down - b.up * a.down, a.down * b.down);
38 }
39 
40 Fraction mul(const Fraction& a, const Fraction& b) {
41     return Fraction(a.up * b.up, a.down * b.down);
42 }
43 
44 Fraction div(const Fraction& a, const Fraction& b) {
45     if (b.up == 0) throw std::invalid_argument("Division by zero");
46     return Fraction(a.up * b.down, a.down * b.up);
47 }

  运行结果截图:

image

思考与讨论:

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

 

  我选择友元函数,理由是:通过友元函数可直接访问分数类私有成员,实现简洁直观。

 

posted @ 2025-10-29 01:15  zxy22213  阅读(7)  评论(0)    收藏  举报