• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Nolan-Niko-077
博客园    首页    新随笔    联系   管理    订阅  订阅

实验作业2

四、实验结论

实验内容1

代码1

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     std::cout << "func: T objects'current count: " << T::get_cnt() << '\n';
53 }

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 }

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

运行截图1

运行截图1

问题

问题1

运行截图1-1

报错原因:编译器首先处理#include指令,将头文件内容插入到源文件中。task1.cpp包含了T.h,所以T.h的内容会被复制到task1.cpp中。接着编译器逐个源文——task1.cpp和T.cp进行编译,生成.o文件。在这个过程中,编译器需要知道所有函数和变量的声明,才能检查代码语法和类型匹配。最后将所有目标文件链接成可执行文件,解决函数调用和定义之间的关联。但在编译过程中,在T.h中,有一个友元声明friend void func();,这只在类T的内部有效,它只告诉编译器func是T的友元,可访问T的私有成员。但友元声明并不相当于在全局作用域中声明函数。也就是说,友元声明不会让func在全局范围内可见。当T.h中的普通函数声明void func();被注释掉后,task1.cpp在预处理后就没有任何关于func的全局声明。因此当编译器编译task1.cpp时,遇到func()调用,它不知道func是什么,因为没有任何声明告诉编译器func的存在。虽然T.cpp中定义了func函数,但每个源文件都是独立编译的。编译task1.cpp时,编译器只看到T.h的内容,而T.h中没有func的全局声明,所以报错“'func' was not declared in this scope”。

问题2

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

功能:创建新对象并初始化数据成员,含默认参数,可接受0-2个参数。

调用时机:新对象初始化时。

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

功能:通过已有对象创建新对象。

调用时机:一般在新对象初始化时。

T(T &&t); //移动构造函数

功能:通过右值引用"窃取"临时对象的资源,优化复制。

调用时机:一般在返回临时对象时。

~T();//析构函数

功能:对象销毁时清理资源,维护静态计数。

调用时机:对象离开作用域、程序运行结束时。

问题3

运行截图1-2

原因分析:ODR规定,静态成员变量的定义必须在类外且只能出现一次,当将定义移到T.h末尾后,每个包含T.h的源文件——task1.cpp和T.cpp——都会包含这些定义,所以在链接时,会发现多个编译单元中都有相同的符号定义,导致冲突。具体的过程即因为task1.cpp 包含T.h,所以此时获得静态成员定义,而T.cpp 包含 T.h,会再次获得静态成员定义,最终链接器发现重复定义而报错。

实验内容2

代码2

Complex.h

 1 #pragma once
 2 #include<string>
 3 
 4 class Complex{
 5     public:
 6         // 类属性
 7         static const std::string doc;
 8         
 9         // 构造函数
10         Complex(double real_val = 0.0, double imag_val = 0.0); //普通构造函数 
11         Complex(const Complex& other);// 拷贝构造函数
12         
13         // 成员函数
14         double get_real() const;
15         double get_imag() const;
16         void add(const Complex& other);
17         
18         // 友元函数声明
19         friend void output(const Complex& c);
20         friend double abs(const Complex& c);
21         friend Complex add(const Complex& c1, const Complex& c2);
22         friend bool is_equal(const Complex& c1, const Complex& c2);
23         friend bool is_not_equal(const Complex& c1, const Complex& c2);
24         
25     private:
26         double real;
27         double imag;
28 };

Complex.cpp

 1 #include "Complex.h"
 2 #include <cmath>
 3 #include <iostream>
 4 
 5 using namespace std;
 6 
 7 // 类属性定义
 8 const string Complex::doc = "a simplified complex class";
 9 
10 // 构造函数实现
11 Complex::Complex(double real_val, double imag_val) : real(real_val), imag(imag_val) {}
12 Complex::Complex(const Complex& other) : real(other.real), imag(other.imag) {}
13 
14 // 成员函数实现
15 double Complex::get_real() const {
16     return real;
17 }
18 
19 double Complex::get_imag() const {
20     return imag;
21 }
22 
23 void Complex::add(const Complex& other) {
24     real += other.real;
25     imag += other.imag;
26 }
27 
28 // 友元函数实现
29 void output(const Complex& c) {
30     cout << c.real << " ";
31     if (c.imag < 0) cout << "- " << -c.imag;
32     else cout << "+ " << c.imag;
33     cout << "i";
34 }
35 
36 double abs(const Complex& c) {
37     return sqrt(c.real * c.real + c.imag * c.imag);
38 }
39 
40 Complex add(const Complex& c1, const Complex& c2) {
41     return Complex(c1.real + c2.real, c1.imag + c2.imag);
42 }
43 
44 bool is_equal(const Complex& c1, const Complex& c2) {
45     // 浮点数比较使用容差
46     const double epsilon = 1e-10;
47     return (fabs(c1.real - c2.real) < epsilon) && 
48            (fabs(c1.imag - c2.imag) < epsilon);
49 }
50 
51 bool is_not_equal(const Complex& c1, const Complex& c2) {
52     return !is_equal(c1, c2);
53 }

task2.cpp

 1 // 待补足头文件
 2 // xxx
 3 #include "Complex.h" 
 4 
 5 #include <iostream>
 6 #include <iomanip>
 7 #include <complex>
 8 
 9 void test_Complex();
10 void test_std_complex();
11 
12 int main() {
13     std::cout << "*******测试1: 自定义类Complex*******\n";
14     test_Complex();
15 
16     std::cout << "\n*******测试2: 标准库模板类complex*******\n";
17     test_std_complex();
18 }
19 
20 void test_Complex() {
21     using std::cout;
22     using std::endl;
23     using std::boolalpha;
24 
25     cout << "类成员测试: " << endl;
26     cout << Complex::doc << endl << endl;
27 
28     cout << "Complex对象测试: " << endl;
29     Complex c1;
30     Complex c2(3, -4);
31     Complex c3(c2);
32     Complex c4 = c2;
33     const Complex c5(3.5);
34 
35     cout << "c1 = "; output(c1); cout << endl;
36     cout << "c2 = "; output(c2); cout << endl;
37     cout << "c3 = "; output(c3); cout << endl;
38     cout << "c4 = "; output(c4); cout << endl;
39     cout << "c5.real = " << c5.get_real() 
40          << ", c5.imag = " << c5.get_imag() << endl << endl;
41 
42     cout << "复数运算测试: " << endl;
43     cout << "abs(c2) = " << abs(c2) << endl;
44     c1.add(c2);
45     cout << "c1 += c2, c1 = "; output(c1); cout << endl;
46     cout << boolalpha;
47     cout << "c1 == c2 : " << is_equal(c1, c2) << endl;
48     cout << "c1 != c2 : " << is_not_equal(c1, c2) << endl;
49     c4 = add(c2, c3);
50     cout << "c4 = c2 + c3, c4 = "; output(c4); cout << endl;
51 }
52 
53 void test_std_complex() {
54     using std::cout;
55     using std::endl;
56     using std::boolalpha;
57 
58     cout << "std::complex<double>对象测试: " << endl;
59     std::complex<double> c1;
60     std::complex<double> c2(3, -4);
61     std::complex<double> c3(c2);
62     std::complex<double> c4 = c2;
63     const std::complex<double> c5(3.5);
64 
65     cout << "c1 = " << c1 << endl;
66     cout << "c2 = " << c2 << endl;
67     cout << "c3 = " << c3 << endl;
68     cout << "c4 = " << c4 << endl;
69 
70     cout << "c5.real = " << c5.real() 
71          << ", c5.imag = " << c5.imag() << endl << endl;
72 
73     cout << "复数运算测试: " << endl;
74     cout << "abs(c2) = " << abs(c2) << endl;
75     c1 += c2;
76     cout << "c1 += c2, c1 = " << c1 << endl;
77     cout << boolalpha;
78     cout << "c1 == c2 : " << (c1 == c2)<< endl;
79     cout << "c1 != c2 : " << (c1 != c2) << endl;
80     c4 = c2 + c3;
81     cout << "c4 = c2 + c3, c4 = " << c4 << endl;
82 }

运行截图2

运行截图2

问题

问题1

标准库模板类complex的使用形式更简洁,函数和运算有内在关联,运算符重载能更自然地表达数学运算的语义,使代码更直观易懂。

问题2

2-1

否。这些函数可以通过公有接口get_real()和get_imag()实现,无需直接访问私有数据。友元破坏了封装性。

2-2

运行截图2-1

否。查阅cppreference可知,std::complex的abs函数是非成员函数,通过公有成员函数real()和imag()访问数据。

2-3

应该使用friend的原则为,优先考虑公有接口,实在无法实现时才使用friend。

使用friend的情况如下。

1.输入输出运算符<< 和 >> 必须是非成员函数,且需要访问私有数据。

2.需要对称性的运算符,如 a + b 和 b + a 应该行为一致。

3.需要访问多个类私有数据的函数。

应该避免使用friend的情况如下。

1.函数可以通过公有接口完成功能时。

2.只是为了方便而破坏封装性时。

问题3

将拷贝构造函数声明为explicit,即explicit Complex(const Complex& other);。

explicit关键字告诉编译器,不允许隐式转换、隐式调用。这样Complex c4 = c2;会编译报错,而Complex c4(c2);仍可用。

实验内容3

代码3

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 }

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 // 待补足
10 // 1. 将输入字符串转为小写,实现大小写不敏感
11 // 2. 匹配"play"/"pause"/"next"/"prev"/"stop"并返回对应枚举
12 // 3. 未匹配的字符串返回ControlType::Unknown
13 // 4. 每次成功调用parse时递增total_cnt
14 ControlType PlayerControl::parse(const std::string& control_str) {
15     // xxx
16     // 递增总计数
17     total_cnt++;
18     
19     // 将输入字符串转为小写
20     std::string lower_str = control_str;
21     std::transform(lower_str.begin(), lower_str.end(), lower_str.begin(),
22                    [](unsigned char c){ return std::tolower(c); });
23     
24     // 匹配控制命令
25     if (lower_str == "play") {
26         return ControlType::Play;
27     } else if (lower_str == "pause") {
28         return ControlType::Pause;
29     } else if (lower_str == "next") {
30         return ControlType::Next;
31     } else if (lower_str == "prev") {
32         return ControlType::Prev;
33     } else if (lower_str == "stop") {
34         return ControlType::Stop;
35     } else {
36         return ControlType::Unknown;
37     }
38 }
39 
40 void PlayerControl::execute(ControlType cmd) const {
41     switch (cmd) {
42     case ControlType::Play:  std::cout << "[play] Playing music...\n"; break;
43     case ControlType::Pause: std::cout << "[Pause] Music paused\n";    break;
44     case ControlType::Next:  std::cout << "[Next] Skipping to next track\n"; break;
45     case ControlType::Prev:  std::cout << "[Prev] Back to previous track\n"; break;
46     case ControlType::Stop:  std::cout << "[Stop] Music stopped\n"; break;
47     default:                 std::cout << "[Error] unknown control\n"; break;
48     }
49 }
50 
51 int PlayerControl::get_cnt() {
52     return total_cnt;
53 }

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 };

运行截图3

运行截图3

思考

控制台默认使用的编码不是UTF-8,而做作业都要用到古老的原版c++以及相关的工具链,贸然改一些默认设置,或者加一些可实现“在指定位置打印图片”的库,可能会使得以后的平时作业、考试变得不可预测、玄学起来,所以这里都换成基于控制台所支持的字符,作为下为替代:运行截图3-1

实验内容4

代码4

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

Fraction.h

 1 #pragma once
 2 
 3 #include <string>
 4 
 5 class Fraction {
 6     public:
 7         static const std::string doc;
 8         
 9         // 构造函数
10         Fraction(int up = 0, int down = 1);
11         Fraction(const Fraction& other);
12         
13         // 访问器
14         int get_up() const;
15         int get_down() const;
16         
17         // 求负运算
18         Fraction negative() const;
19         
20     private:
21         int up;     // 分子
22         int down;   // 分母
23         
24         // 内部工具函数
25         void reduce();      // 约分
26         int gcd(int a, int b) const; // 最大公约数
27 };
28 
29 // 自由函数声明
30 void output(const Fraction& f);
31 Fraction add(const Fraction& f1, const Fraction& f2);
32 Fraction sub(const Fraction& f1, const Fraction& f2);
33 Fraction mul(const Fraction& f1, const Fraction& f2);
34 Fraction div(const Fraction& f1, const Fraction& f2);

fraction.cpp

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

运行截图4

运行截图4

问题

我设计的方案是命名空间+自由函数,因为自由函数通过公有接口访问数据,保持了良好的封装性。可以轻松添加新的工具函数而无需修改类定义。如果使用友元,则直接访问私有成员,破坏封装性。当类结构改变时,可能所有友元函数都需要相应修改。而如果使用静态成员函数,则会增加类的接口复杂度,而且静态成员函数属于类而非对象,语义上不够自然,主要是,对于纯工具函数,更适合作为外部函数。用命名空间是为了避免全局命名空间污染,以及逻辑上相关的函数可以组织在一起,这样维护起来会方便不少。传递参数时,通过常量引用传递参数,避免不必要的复制,约分操作在构造函数中完成,确保对象始终处在最简形式。

五、实验总结

感觉对OOP更熟悉了。

posted @ 2025-10-28 10:29  NolanNiko  阅读(11)  评论(1)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3