实验2

实验任务1源代码:

 1 #pragma once
 2 #include <string>
 3 // 类T: 声明
 4 class T {
 5     // 对象属性、方法
 6 public:
 7     T(int x = 0, int y = 0);   // 普通构造函数
 8     T(const T& t);  // 复制构造函数
 9     T(T&& t);
10     // 移动构造函数
11     ~T();
12     // 析构函数
13     void adjust(int ratio);
14     void display() const;
15 private:
16     int m1, m2;
17     // 类属性、方法
18 public:
19     static int get_cnt();
20 public:
21     static const std::string doc;
22     static const int max_cnt;
23 private:
24     static int cnt;
25     // 按系数成倍调整数据
26     // 以(m1, m2)形式显示T类对象信息
27     // 显示当前T类对象总数
28     // 类T的描述信息
29     // 类T对象上限
30     // 当前T类对象数目
31     // 类T友元函数声明
32     friend void func();
33 };
34 // 普通函数声明
35 void func();
T.h
 1 #include "T.h"
 2 #include <iostream>
 3 #include <string>
 4 // 类T实现
 5 // static成员数据类外初始化
 6 const std::string T::doc{ "a simple class sample" };
 7 const int T::max_cnt = 999;
 8 int T::cnt = 0;
 9 // 类方法
10 int T::get_cnt() {
11     return cnt;
12 }
13 // 对象方法
14 T::T(int x, int y) : m1{ x }, m2{ y } {
15     ++cnt;
16     std::cout << "T constructor called.\n";
17 }
18 T::T(const T& t) : m1{ t.m1 }, m2{ t.m2 } {
19     ++cnt;
20     std::cout << "T copy constructor called.\n";
21 }
22 T::T(T&& t) : m1{ t.m1 }, m2{ t.m2 } {
23     ++cnt;
24     std::cout << "T move constructor called.\n";
25 }
26 T::~T() {
27     --cnt;
28     std::cout << "T destructor called.\n";
29 }
30 void T::adjust(int ratio) {
31     m1 *= ratio;
32     m2 *= ratio;
33 }
34 void T::display() const {
35     std::cout << "(" << m1 << ", " << m2 << ")";
36 }
37 // 普通函数实现
38 void func() {
39     T t5(42);
40     t5.m2 = 2049;
41     std::cout << "t5 = "; t5.display(); std::cout << '\n';
42 }
T.cpp
 1 #include "T.h"
 2 #include <iostream>
 3 void test_T();
 4 int main() {
 5     std::cout << "test Class T: \n";
 6     test_T();
 7 
 8     std::cout << "\ntest friend func: \n";
 9     func();
10 }
11 void test_T() {
12     using std::cout;
13     using std::endl;
14     cout << "T info: " << T::doc << endl;
15     cout << "T objects'max count: " << T::max_cnt << endl;
16     cout << "T objects'current count: " << T::get_cnt() << endl << endl;
17     T t1;
18     cout << "t1 = "; t1.display(); cout << endl;
19     T t2(3, 4);
20     cout << "t2 = "; t2.display(); cout << endl;
21     T t3(t2);
22     t3.adjust(2);
23     cout << "t3 = "; t3.display(); cout << endl;
24     T t4(std::move(t2));
25     cout << "t4 = "; t4.display(); cout << endl;
26     cout << "test: T objects'current count: " << T::get_cnt() << endl;
27 }
task1.cpp

 

运行结果:

QQ_1761279119979

问题1回答:编译出错,无法运行。友元函数本质上是一个普通函数被授予了访问该类的私有和保护成员的权限,需要正常在类外部声明。

QQ_1761279332641

问题2回答:

1、普通构造函数:在对象创建时初始化其成员变量,为对象设点初始状态

2、复制构造函数:拷贝一个已存在的对象来初始化一个对象,创建该对象的副本

3、移动构造函数:将资源从一个右值转移给新对象,避免不必要的深拷贝

4、析构函数:在对象销毁时自动调用,负责清理资源

问题3回答:C++要求非内联函数在整个程序中只能有一处定义,此代码改动后是在头文件中定义,导致多个源文件同时包含T.h头文件时都会重新定义一次T::get_cnt(),因此报错“重复定义”

QQ_1761279743091

 

实验任务2源代码:

 1 #include"Complex.h"
 2 #include <iostream>
 3 #include <iomanip>
 4 #include <complex>
 5 void test_Complex();
 6 void test_std_complex();
 7 int main() {
 8     std::cout << "*******测试1: 自定义类Complex*******\n";
 9     test_Complex();
10     std::cout << "\n*******测试2: 标准库模板类complex*******\n";
11     test_std_complex();
12 }
13 void test_Complex() {
14     using std::cout;
15     using std::endl;
16     using std::boolalpha;
17     cout << "类成员测试: " << endl;
18     cout << Complex::doc << endl << endl;
19     cout << "Complex对象测试: " << endl;
20     Complex c1;
21     Complex c2(3, -4);
22     Complex c3(c2);
23     Complex c4 = c2;
24     const Complex c5(3.5);
25     cout << "c1 = "; output(c1); cout << endl;
26     cout << "c2 = "; output(c2); cout << endl;
27     cout << "c3 = "; output(c3); cout << endl;
28     cout << "c4 = "; output(c4); cout << endl;
29     cout << "c5.real = " << c5.get_real()
30         << ", c5.imag = " << c5.get_imag() << endl << endl;
31     cout << "复数运算测试: " << endl;
32     cout << "abs(c2) = " << abs(c2) << endl;
33     c1.add(c2);
34     cout << "c1 += c2, c1 = "; output(c1); cout << endl;
35     cout << boolalpha;
36     cout << "c1 == c2 : " << is_equal(c1, c2) << endl;
37     cout << "c1 != c2 : " << is_not_equal(c1, c2) << endl;
38     c4 = add(c2, c3);
39     cout << "c4 = c2 + c3, c4 = "; output(c4); cout << endl;
40 }
41 void test_std_complex() {
42     using std::cout;
43     using std::endl;
44     using std::boolalpha;
45     cout << "std::complex<double>对象测试: " << endl;
46     std::complex<double> c1;
47     std::complex<double> c2(3, -4);
48     std::complex<double> c3(c2);
49     std::complex<double> c4 = c2;
50     const std::complex<double> c5(3.5);
51     cout << "c1 = " << c1 << endl;
52     cout << "c2 = " << c2 << endl;
53     cout << "c3 = " << c3 << endl;
54     cout << "c4 = " << c4 << endl;
55     cout << "c5.real = " << c5.real()
56         << ", c5.imag = " << c5.imag() << endl << endl;
57     cout << "复数运算测试: " << endl;
58     cout << "abs(c2) = " << abs(c2) << endl;
59     c1 += c2;
60     cout << "c1 += c2, c1 = " << c1 << endl;
61     cout << boolalpha;
62     cout << "c1 == c2 : " << (c1 == c2) << endl;
63     cout << "c1 != c2 : " << (c1 != c2) << endl;
64     c4 = c2 + c3;
65     cout << "c4 = c2 + c3, c4 = " << c4 << endl;
66 }
task2.cpp
 1 #pragma once
 2 #include<string>
 3 #include<cmath>
 4 
 5 class Complex {
 6 private:
 7     double real, imag;
 8 
 9 public:
10     static const std::string doc;
11 
12     Complex(double real = 0.0, double imag = 0.0);
13     Complex(const Complex& other);
14 
15     double get_real() const { return real; }
16     double get_imag() const { return imag; }
17     Complex& add(const Complex& other);
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 
26 void output(const Complex& c);
27 double abs(const Complex& c);
28 Complex add(const Complex& c1, const Complex& c2);
29 bool is_equal(const Complex& c1, const Complex& c2);
30 bool is_not_equal(const Complex& c1, const Complex& c2);
Complex.h
 1 #include"Complex.h"
 2 #include<string>
 3 #include<iostream>
 4 
 5 const std::string Complex::doc{ "a simpled complex class" };
 6 
 7 Complex::Complex(double real_, double imag_): real(real_), imag(imag_) {
 8 
 9 }
10 
11 Complex::Complex(const Complex& other) {
12     real = other.real;
13     imag = other.imag;
14 }
15 
16 Complex& Complex::add(const Complex& other) {
17     real += other.real;
18     imag += other.imag;
19     return *this;
20 }
21 
22 void output(const Complex& c) {
23     std::cout << c.get_real();
24     if (c.get_imag() >= 0) {
25         std::cout << " + " << c.get_imag() << "i";
26     }
27     else {
28         std::cout << " - " << -c.get_imag() << "i";
29     }
30 }
31 
32 double abs(const Complex& c) {
33     return std::sqrt(c.get_real() * c.get_real() + c.get_imag() * c.get_imag());
34 }
35 
36 Complex add(const Complex& c1, const Complex& c2) {
37     return Complex(c1.get_real() + c2.get_real(), c1.get_imag() + c2.get_imag());
38 }
39 
40 bool is_equal(const Complex& c1, const Complex& c2) {
41     return (c1.get_real() == c2.get_real()) && (c1.get_imag() == c2.get_imag());
42 }
43 
44 bool is_not_equal(const Complex& c1, const Complex& c2) {
45     return !is_equal(c1, c2);
46 }
Complex.cpp

运行结果:

QQ_1761655334208

问题1回答:标准模板库更简洁,核心思想都是将复数的运算变为编程语言方便使用

问题2回答:

  2-1:是,类的封装性要求其私有成员只能被该类的​​成员函数​​直接访问,而这些函数从设计逻辑上更适合作为全局函数存在,但它们的工作又必须依赖于对象的内部私有数据,故设置为友元函数。

  2-2:不是,是独立的非成员函数模板。

  2-3:友元机制是在“需要保持非成员身份,又不得不突破封装限制以完成特定功能”的场景下,提供的一种精密控制的解决方案。它平衡了封装性和灵活性,使得非成员函数能够在不成为类成员的情况下,高效地完成任务。

问题3回答:禁用类的拷贝构造函数

 

实验任务3源代码:

 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 }
task3.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     std::string lower_str = control_str;
 9     std::transform(lower_str.begin(), lower_str.end(), lower_str.begin(),[](unsigned char c) { return std::tolower(c); });
10 
11     ControlType result = ControlType::Unknown;
12 
13     if (lower_str == "play") {
14         result = ControlType::Play;
15     }
16     else if (lower_str == "pause") {
17         result = ControlType::Pause;
18     }
19     else if (lower_str == "next") {
20         result = ControlType::Next;
21     }
22     else if (lower_str == "prev") {
23         result = ControlType::Prev;
24     }
25     else if (lower_str == "stop") {
26         result = ControlType::Stop;
27     }
28     else {
29         result = ControlType::Unknown;
30     }
31 
32     if (result != ControlType::Unknown) {
33         total_cnt++;
34     }
35 
36     return result;
37 }
38 void PlayerControl::execute(ControlType cmd) const {
39     switch (cmd) {
40     case ControlType::Play:  std::cout << "[play] Playing music...\n"; break;
41     case ControlType::Pause: std::cout << "[Pause] Music paused\n";    break;
42     case ControlType::Next:  std::cout << "[Next] Skipping to next track\n"; break;
43     case ControlType::Prev:  std::cout << "[Prev] Back to previous track\n"; break;
44     case ControlType::Stop:  std::cout << "[Stop] Music stopped\n"; break;
45     default:                 std::cout << "[Error] unknown control\n"; break;
46     }
47 }
48 int PlayerControl::get_cnt() {
49     return total_cnt;
50 }
PlayerControl.cpp
 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     static int get_cnt();
11     ControlType parse(const std::string& control_str);   // 实现std::string --> ControlType转换
12     void execute(ControlType cmd) const;   // 执行控制操作(以打印输出模拟)
13 
14 
15 private:
16     static int total_cnt;
17 };
PlayerControl.h

 

运行结果:

QQ_1761655992166

 

实验任务4源代码:

 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 
15     cout << "Fraction类测试: " << endl;
16     cout << Fraction::doc << endl << endl;
17 
18     Fraction f1(5);
19     Fraction f2(3, -4), f3(-18, 12);
20     Fraction f4(f3);
21     cout << "f1 = "; output(f1); cout << endl;
22     cout << "f2 = "; output(f2); cout << endl;
23     cout << "f3 = "; output(f3); cout << endl;
24     cout << "f4 = "; output(f4); cout << endl;
25 
26     const Fraction f5(f4.negative());
27     cout << "f5 = "; output(f5); cout << endl;
28     cout << "f5.get_up() = " << f5.get_up()
29         << ", f5.get_down() = " << f5.get_down() << endl;
30 
31     cout << "f1 + f2 = "; output(add(f1, f2)); cout << endl;
32     cout << "f1 - f2 = "; output(sub(f1, f2)); cout << endl;
33     cout << "f1 * f2 = "; output(mul(f1, f2)); cout << endl;
34     cout << "f1 / f2 = "; output(div(f1, f2)); cout << endl;
35     cout << "f4 + f5 = "; output(add(f4, f5)); cout << endl;
36 }
37 void test2() {
38     using std::cout;
39     using std::endl;
40     Fraction f6(42, 55), f7(0, 3);
41     cout << "f6 = "; output(f6); cout << endl;
42     cout << "f7 = "; output(f7); cout << endl;
43     cout << "f6 / f7 = "; output(div(f6, f7)); cout << endl;
44 }
task4.cpp
 1 #pragma once
 2 #include<string>
 3 
 4 class Fraction {
 5 public:
 6     static const std::string doc;
 7 
 8     Fraction(int upNum = 0, int downNum = 1);
 9     Fraction(const Fraction &other);
10 
11     int get_up() const { return up; };
12     int get_down() const { return down; };
13     Fraction negative() const;
14 
15     friend Fraction add(const Fraction& f1, const Fraction& f2);
16     friend Fraction sub(const Fraction& f1, const Fraction& f2);
17     friend Fraction mul(const Fraction& f1, const Fraction& f2);
18     friend Fraction div(const Fraction& f1, const Fraction& f2);
19     friend void output(const Fraction& f);
20 
21 private:
22     int up, down;
23 
24     //简化分数,即约分
25     void simplify();
26 };
27 
28 Fraction add(const Fraction& f1, const Fraction& f2);
29 Fraction sub(const Fraction& f1, const Fraction& f2);
30 Fraction mul(const Fraction& f1, const Fraction& f2);
31 Fraction div(const Fraction& f1, const Fraction& f2);
32 void output(const Fraction& f);
33 
34 //最大公约数
35 int gcd(int a, int b);
Fraction.h
 1 #include"Fraction.h"
 2 #include<iostream>
 3 #include<cmath>
 4 #include<string>
 5 
 6 const std::string Fraction::doc{"Fraction类v 0.01版本\n目前仅支持分数对象的构造、输出、加/减/乘/除运算"};
 7 
 8 //求取最大公约数
 9 int gcd(int a, int b) {
10     a = std::abs(a);
11     b = std::abs(b);
12     while (b != 0) {
13         int temp = b;
14         b = a % b;
15         a = temp;
16     }
17     return a;
18 }
19 
20 //分数约分
21 void Fraction::simplify() {
22     if (down == 0) return;
23 
24     if (down < 0) {
25         up = -up;
26         down = -down;
27     }
28     
29     int common = gcd(up, down);
30     if (common != 0) {
31         up /= common;
32         down /= common;
33     }
34 
35     if (up == 0) {
36         down = 1;
37     }
38 }
39 
40 Fraction::Fraction(int upNum, int downNum):up(upNum), down(downNum) {
41     if (down == 0) {
42         std::cout << "分母不能为0!" << std::endl;
43     }
44     simplify();
45 }
46 
47 Fraction::Fraction(const Fraction& other): up(other.up), down(other.down) {
48 
49 }
50 
51 Fraction Fraction::negative() const {
52     return Fraction(-up, down);
53 }
54 
55 Fraction add(const Fraction& f1, const Fraction& f2) {
56     int new_up = f1.get_up() * f2.get_down() + f2.get_up() * f1.get_down();
57     int new_down = f1.get_down() * f2.get_down();
58     return Fraction(new_up, new_down);
59 }
60 
61 Fraction sub(const Fraction& f1, const Fraction& f2) {
62     int new_up = f1.get_up() * f2.get_down() - f2.get_up() * f1.get_down();
63     int new_down = f1.get_down() * f2.get_up();
64     return Fraction(new_up, new_down);
65 }
66 
67 Fraction mul(const Fraction& f1, const Fraction& f2) {
68     int new_up = f1.get_up() * f2.get_up();
69     int new_down = f1.get_down() * f2.get_down();
70     return Fraction(new_up, new_down);
71 }
72 
73 Fraction div(const Fraction& f1, const Fraction& f2) {
74     if (f2.up == 0) {
75         std::cout << "不能除以0!";
76     }
77     int new_up = f1.get_up() * f2.get_down();
78     int new_down = f1.get_down() * f2.get_up();
79     return Fraction(new_up, new_down);
80 }
81     
82 
83 void output(const Fraction& f) {
84     if (f.get_down() == 1) {
85         std::cout << f.get_up();
86     }
87     else {
88         std::cout << f.get_up() << "/" << f.get_down();
89     }
90 }
Fraction.cpp

运行结果:

QQ_1761653214653

问题回答:我使用了命名空间+自由函数,因为这样封装性更好、灵活性更高,通过公有接口访问数据,保证了类私有数据安全

posted on 2025-10-28 20:55  豪雅  阅读(5)  评论(1)    收藏  举报