实验2

实验任务1:

源代码T.h

 1 #pragma once
 2 #include<string>
 3 
 4 class T{
 5     public:
 6         T(int x=0,int y=0);
 7         T(const T &t);
 8         T(T &&t);
 9         ~T();
10         
11         void adjust(int ratio);
12         void display() const;
13         
14     private:
15         int m1,m2;
16     
17     public:
18         static int get_cnt();
19         
20     public:
21         static const std::string doc;
22         static const int max_cnt;
23         
24     private:
25         static int cnt;
26         
27     friend void func();
28 }; 
29 
30 void func();

源代码T.cpp

 1 #include "T.h"
 2 #include<iostream>
 3 #include<string>
 4 
 5 const std::string T::doc {
 6     "a simple class sample"
 7 };
 8 const int T::max_cnt=999;
 9 int T::cnt=0;
10 
11 int T::get_cnt() {
12     return cnt;
13 }
14 
15 T::T(int x,int y):m1 {x},m2 {y} {
16     ++cnt;
17     std::cout << "T constructor called.\n";
18 }
19 
20 T::T(const T &t):m1{t.m1},m2{t.m2}{
21     ++cnt;
22     std::cout << "T copy constructor called.\n";
23 }
24 
25 T::T(T &&t):m1{t.m1},m2{t.m2}{
26    ++cnt;
27    std::cout << "T move constructor called.\n";
28 }
29 
30 T::~T(){
31     --cnt;
32     std::cout << "T destructor called.\n";
33 }
34 
35 void T::adjust(int ratio){
36     m1*=ratio;
37     m2*=ratio;
38 }
39 
40 void T::display() const {
41     std::cout << "(" << m1 << "," << m2 << ")";
42 }
43 
44 void func(){
45     T t5(42);
46     t5.m2=2049;
47     std::cout << "t5 = ";
48     t5.display();
49     std::cout << '\n';
50 }

源代码task1.cpp

 1 #include "T.h"
 2 #include<iostream>
 3 
 4 void tset_T();
 5 
 6 int main(){
 7     std::cout << "tset class T:\n";
 8     tset_T();
 9     
10     std::cout << "\ntest fried 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.类内的友元声明不替代函数的全局声明,去掉 line36 后,全局作用域中无 func 的原型声明,调用时编译器无法识别该函数。Dev-C++没有报错,是编译器兼容性的宽松处理。

问题2:

普通构造函数:

功能:初始化类 T 的对象,为成员变量分配初始值。

调用时机:当创建类 T 的对象时自动调用。

复制构造函数:

功能:用已存在的类 T 对象,拷贝其数据来初始化新的类 T 对象。

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

移动构造函数:

功能:“窃取”右值对象( t )的资源,来初始化新的类 T 对象。

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

析构函数:

功能:对象生命周期结束时,释放对象占用的资源。

调用时机:局部对象离开其作用域时;程序结束时,全局/静态对象被销毁时。

问题3:

程序不能正确编译,会出现重复定义错误。但是Dev-C++没报错,是因为当前项目中只包含了一个.cpp文件,没有多个文件重复包含T.h,所以没触发“重复定义”的链接错误。

 

实验任务2:

 源代码Complex.h

 1 #pragma once
 2 #include<string>
 3 
 4 class Complex{
 5     public:
 6         static const std::string doc;
 7         Complex();
 8         Complex(double Real);
 9         Complex(double Real,double Imag);
10         Complex(const Complex &other);
11         Complex &operator=(const Complex &other);
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         friend Complex add(const Complex &c1,const Complex &c2);
20         friend bool is_equal(const Complex &c1,const Complex &c2);
21         friend bool is_not_equal(const Complex &c1,const Complex &c2);
22         
23     private:
24         double real,imag;    
25 };

源代码Complex.cpp

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

源代码task2.cpp

 1 // 待补足头文件
 2 
 3 #include "Complex.h"
 4 #include <iostream>
 5 #include <iomanip>
 6 #include <complex>
 7 
 8 void test_Complex();
 9 void test_std_complex();
10 
11 int main() {
12     std::cout << "*******测试1: 自定义类Complex*******\n";
13     test_Complex();
14 
15     std::cout << "\n*******测试2: 标准库模板类complex*******\n";
16     test_std_complex();
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 
69     cout << "c5.real = " << c5.real() 
70          << ", c5.imag = " << c5.imag() << endl << endl;
71 
72     cout << "复数运算测试: " << endl;
73     cout << "abs(c2) = " << abs(c2) << endl;
74     c1 += c2;
75     cout << "c1 += c2, c1 = " << c1 << endl;
76     cout << boolalpha;
77     cout << "c1 == c2 : " << (c1 == c2)<< endl;
78     cout << "c1 != c2 : " << (c1 != c2) << endl;
79     c4 = c2 + c3;
80     cout << "c4 = c2 + c3, c4 = " << c4 << endl;
81 }

运行结果截图:

image

image

问题1:

在使用形式上,标准库模板类 complex 更简洁。函数和运算内在有关联:标准库的运算本质是通过重载运算符函数实现的,只是语法形式更接近自然运算。

问题2:

2-1:是。output 需要输出 real / imag , abs 需要计算 real²+imag² , add 需要获取 real / imag 做加法——这些操作都依赖类的私有成员 real 和 imag ,因此需要设为友元来访问私有数据。

2-2:否。标准库 std::complex 的 abs 函数并非友元,而是通过类的公共接口获取实部、虚部后计算的。

2-3:函数/类需要访问当前类的私有/保护成员,且无法通过公共接口实现;实现不同类之间的协作。

问题3:

为 Complex 类添加拷贝构造函数。

 

实验任务3:

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

源代码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

 

实验任务4:

源代码Fraction.h

 1 #pragma once
 2 #include<string>
 3 
 4 class Fraction{
 5     public:
 6         static const std::string doc;
 7         Fraction(int up_v);
 8         Fraction(int up_v,int down_v);
 9         Fraction(const Fraction &other);
10         int get_up()const;
11         int get_down()const;
12         Fraction negative()const;
13         friend void output(const Fraction &f);
14         friend Fraction add(const Fraction &f1,const Fraction &f2);
15         friend Fraction sub(const Fraction &f1,const Fraction &f2);
16         friend Fraction mul(const Fraction &f1,const Fraction &f2);
17         friend Fraction div(const Fraction &f1,const Fraction &f2);
18     private:
19         int up,down;
20         void simplify();
21         static int gcd(int a,int b);
22 };

源代码Fraction.cpp

 1 #include "Fraction.h"
 2 #include<iostream>
 3 #include<stdexcept>
 4 
 5 const std::string Fraction::doc="Fraction类 v 0.01版.\n目前仅支持分数对象的构造、输出、加/减/乘/除运算.";
 6 int Fraction::gcd(int a,int b){
 7     a=abs(a);
 8     b=abs(b);
 9     while(b!=0){
10         int temp=b;
11         b=a%b;
12         a=temp;
13     }
14     return a;
15 }
16 void Fraction::simplify(){
17     if(down==0)
18         throw std::invalid_argument("分母不能为0!");
19     if(down<0){
20         up=-up;
21         down=-down;
22     } 
23     int common_div=gcd(up,down);
24     if(common_div!=0){
25         up/=common_div;
26         down/=common_div;
27     }
28 }
29 Fraction::Fraction(int up_v):up(up_v),down(1){
30     simplify();
31 }
32 Fraction::Fraction(int up_v,int down_v):up(up_v),down(down_v){
33     simplify();
34 }
35 Fraction::Fraction(const Fraction &other):up(other.up),down(other.down){
36 }
37 int Fraction::get_up()const{
38     return up;
39 }
40 int Fraction::get_down()const{
41     return down;
42 }
43 Fraction Fraction::negative()const{
44    return Fraction(-up,down);
45 }
46 void output(const Fraction &f){
47     if(f.up==0)
48        std::cout << f.up;
49     else if(f.down==1)
50        std::cout << f.up;
51     else
52         std::cout << f.up << "/" << f.down;
53 }
54 Fraction add(const Fraction &f1,const Fraction &f2){
55     int new_up=f1.up*f2.down+f2.up*f1.down;
56     int new_down=f1.down*f2.down;
57     return Fraction(new_up,new_down);
58 }
59 Fraction sub(const Fraction &f1,const Fraction &f2){
60     int new_up=f1.up*f2.down-f2.up*f1.down;
61     int new_down=f1.down*f2.down;
62     return Fraction(new_up,new_down);
63 }
64 Fraction mul(const Fraction &f1,const Fraction &f2){
65     int new_up=f1.up*f2.up;
66     int new_down=f1.down*f2.down;
67     return Fraction(new_up,new_down);
68 }
69 Fraction div(const Fraction &f1,const Fraction &f2){
70     if(f2.up==0)
71        throw std::invalid_argument("分母不能为0!"); 
72     int new_up=f1.up*f2.down;
73     int new_down=f1.down*f2.up;
74     return Fraction(new_up,new_down);
75 }

源代码task4.cpp

 1 #include "Fraction.h"
 2 #include <iostream>
 3 #include<stdexcept>
 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 = "; 
50     try{
51         Fraction result=div(f6,f7);
52         output(result);
53     }catch(const std::invalid_argument& e){
54         cout << e.what();
55     }
56     cout << endl;
57 }

运行结果截图:

image

问题:

选择友元。优点:可以直接访问类的私有成员,更符合数学运算的直观写法,代码可读性高。缺点:破坏了封装性。

 

实验总结:

本次实验学习了如何设计类,并正确使用类,友元函数。在进行验证性实验时要注意代码的正确性和规范性,敲代码时要仔细认真,否则容易因名称敲错或者其它小细节导致代码运行失败;构造函数时对于默认值处理方面,单参数构造函数必须显式初始化所有成员变量,否则会导致未定义行为。在进行实验任务4时就是因为未初始化down,导致其默认值为0,无法正确输出分数,运行结果出错。

 

posted @ 2025-10-28 00:25  知之为吃吃  阅读(19)  评论(1)    收藏  举报