实验2 类和对象_基础编程1

任务1:

代码组织:

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

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

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

t.h

 1 #pragma once
 2 
 3 #include <string>
 4 
 5 class T {
 6 public:
 7     T(int x = 0, int y = 0);   // 普通构造函数
 8     T(const T &t);  // 复制构造函数
 9     T(T &&t);       // 移动构造函数
10     ~T();           // 析构函数
11 
12     void adjust(int ratio);      // 按系数成倍调整数据
13 
14     static int get_cnt();          // 显示当前T类对象总数
15 
16     friend void output(const T &t); // 友元, 以(m1, m2)形式输出对象t
17 
18     static const std::string doc;       // 类T的描述信息
19     static const int MAX_CNT;           // 类T对象上限
20 
21 private:
22     int m1, m2;  // 对象数据成员
23 
24     static int current_cnt;    // 当前T类对象数目
25 };

t.cpp

 1 #include "t.h"
 2 
 3 #include <iostream>
 4 #include <stdexcept>
 5 #include <string>
 6 
 7 // static成员数据: 类内声明、类外初始化
 8 const std::string T::doc{"a simple class sample"};
 9 const int T::MAX_CNT = 999;
10 int T::current_cnt = 0;
11 
12 // 对象方法
13 T::T(int x, int y): m1{x}, m2{y} { 
14     if(current_cnt == MAX_CNT) {
15         throw std::runtime_error("T: maximum object count exceeded");
16     }
17 
18     ++current_cnt; 
19     std::cout << "T constructor called.\n";
20 } 
21 
22 T::T(const T &t): m1{t.m1}, m2{t.m2} {
23     if(current_cnt == MAX_CNT) {
24         throw std::runtime_error("T: maximum object count exceeded");
25     }
26 
27     ++current_cnt;
28     std::cout << "T copy constructor called.\n";
29 }
30 
31 T::T(T &&t): m1{t.m1}, m2{t.m2} {
32     if(current_cnt == MAX_CNT) {
33         throw std::runtime_error("T: maximum object count exceeded");
34     }
35 
36     ++current_cnt;
37     std::cout << "T move constructor called.\n";
38 }    
39 
40 T::~T() {
41     --current_cnt;
42     std::cout << "T destructor called.\n";
43 }           
44 
45 void T::adjust(int ratio) {
46     m1 *= ratio;
47     m2 *= ratio;
48 }      
49 
50 // 类方法
51 int T::get_cnt() {
52    return current_cnt;
53 }
54 
55 // 友元
56 void output(const T &t) {
57     std::cout << "(" << t.m1 << ", " << t.m2 << ")";
58 }

task1.cpp

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

 运行结果截图:

图片

观察与思考:

1.

(1)T(int x = 0, int y = 0); 普通构造函数
    功能:用给定初值创建 T 对象,初始化 m1、m2,并增加对象计数。
    调用时机:定义新对象并给出构造参数,或使用默认参数创建对象时。
    对应:T t1; 使用默认参数触发普通构造函数;T t2(3, 4); 也触发普通构造函数。
(2)T(const T &t); 复制构造函数
    功能:用另一个同类型对象的数据初始化新对象,并增加对象计数。
    调用时机:用同类型左值对象初始化新对象时,例如拷贝初始化、按值传参等。
    对应:T t3(t2); 中 t2 是左值,触发复制构造函数。
(3)T(T &&t); 移动构造函数
    功能:用同类型右值对象的数据初始化新对象,并增加对象计数。
    调用时机:用右值(如临时对象或 std::move(...) 的结果)初始化新对象时。
    对应:T t4(std::move(t2)); 中 std::move(t2) 产生右值,触发移动构造函数。
(4)~T(); 析构函数
    功能:对象销毁时执行清理,并减少对象计数。
    调用时机:对象生命周期结束、离开作用域时自动调用。
    对应:t1、t2、t3、t4 离开 test() 内层作用域时都会触发析构函数,通常按构造逆序销毁。

2.不能编译成功,报错信息截图如下:

图片

 头文件中直接定义了变量,当头文件被多个源文件包含时,每个源文件在编译后都会生成包含这些变量内存分配的独立目标文件。链接器在最后合并这些目标文件时,会发现 T 等变量有多个实体,无法确定使用哪一个,于是报错 multiple definition。

3.

(1)功能是:
    限制 T 类对象总数不超过上限
        MAX_CNT 是类 T 允许创建的对象最大数量,值为 999。
        每次构造对象前,先检查当前对象数 current_cnt 是否已经达到 MAX_CNT。
    达到上限时抛出异常,阻止继续构造
        如果  current_cnt == MAX_CNT ,就抛出  std::runtime_error  异常,异常信息为:
       
 "T: maximum object count exceeded"

 


        这样本次构造失败,不会执行后面的 ++current_cnt,对象计数不会超过上限。
    未达到上限时增加对象计数
        如果没有达到上限,就执行 ++current_cnt,表示又成功创建了一个 T 对象。
     #include <stdexcept>  的作用
        提供 std::runtime_error 异常类的定义。没有包含这个头文件,就不能使用 std::runtime_error。

3. 程序崩溃了。运行结果截图:

图片

 已经完整构造的 t1、t2 会在异常栈展开过程中被正常析构,t3 不会被析构。

任务2:

代码组织:

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

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

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

Complex.h

 1 #pragma once
 2 
 3 #include <string>
 4 
 5 class Complex {
 6 public:
 7     static const std::string doc;
 8 
 9     Complex(double real = 0.0, double imag = 0.0);
10 
11     double real() const;
12     double imag() const;
13     void add(const Complex& other);
14 
15     friend void output(const Complex& value);
16     friend double abs(const Complex& value);
17     friend Complex add(const Complex& lhs, const Complex& rhs);
18     friend bool is_equal(const Complex& lhs, const Complex& rhs);
19     friend bool is_not_equal(const Complex& lhs, const Complex& rhs);
20 
21 private:
22     double real_;
23     double imag_;
24 };

Complex.cpp

 1 #include "Complex.h"
 2 
 3 #include <cmath>
 4 #include <iostream>
 5 
 6 const std::string Complex::doc = "a simplified complex class";
 7 
 8 Complex::Complex(double real, double imag)
 9     : real_(real), imag_(imag) {}
10 
11 double Complex::real() const {
12     return real_;
13 }
14 
15 double Complex::imag() const {
16     return imag_;
17 }
18 
19 void Complex::add(const Complex& other) {
20     real_ += other.real_;
21     imag_ += other.imag_;
22 }
23 
24 void output(const Complex& value) {
25     std::cout << value.real_ << (value.imag_ < 0.0 ? " - " : " + ")
26               << std::abs(value.imag_) << 'i';
27 }
28 
29 double abs(const Complex& value) {
30     return std::hypot(value.real_, value.imag_);
31 }
32 
33 Complex add(const Complex& lhs, const Complex& rhs) {
34     return Complex(lhs.real_ + rhs.real_, lhs.imag_ + rhs.imag_);
35 }
36 
37 bool is_equal(const Complex& lhs, const Complex& rhs) {
38     return lhs.real_ == rhs.real_ && lhs.imag_ == rhs.imag_;
39 }
40 
41 bool is_not_equal(const Complex& lhs, const Complex& rhs) {
42     return !is_equal(lhs, rhs);
43 }

task2.cpp

 1 #include <iomanip>
 2 #include <iostream>
 3 
 4 #include "Complex.h"
 5 
 6 // 测试自定义类Complex
 7 void test_Complex() {
 8     using std::cout;
 9     using std::endl;
10     using std::boolalpha;
11 
12     cout << "类成员测试: " << endl;
13     cout << Complex::doc << endl << endl;
14 
15     cout << "Complex对象测试: " << endl;
16     Complex c1;
17     Complex c2(3, -4);
18     Complex c3(c2);
19     Complex c4 = c2;
20     const Complex c5(3.5);
21     const Complex c6 = 3.5;
22 
23     cout << "c1 = "; output(c1); cout << endl;
24     cout << "c2 = "; output(c2); cout << endl;
25     cout << "c3 = "; output(c3); cout << endl;
26     cout << "c4 = "; output(c4); cout << endl;
27     cout << "c5 = "; output(c5); cout << endl;
28     cout << "c6.real = " << c6.real() 
29          << ", c6.imag = " << c6.imag() << endl << endl;
30 
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 
42 int main() {
43     std::cout << "*******测试: 自定义类Complex*******\n";
44     test_Complex();
45 }

运行结果截图:

图片

 

图片

 观察与思考:

1.

(1)必须加上const关键字。如果不加,编译器会认为 real()/imag() 可能需要修改对象,而 c6 是 const Complex,不能把它当作普通 Complex 使用。

编译报错信息意思为:const Complex* 不能转换为非 const 成员函数所需的 Complex* this。

(2)不能编译通过。

因为 add 的声明是:void add(const Complex& other);

它不是 const 成员函数,并且函数体会修改 real_ 和 imag_。而 c6 是 const Complex,只能调用 const 成员函数。

2. 从使用形式上看,标准库的 std::complex<T> 更为简洁直观。

C++ 中的运算符本质上是函数的另一种表现形式。例如 c1 += c2 等价于调用 c1.operator+=(c2) 或 operator+=(c1, c2),c4 = c2 + c3 等价于 operator+(c2, c3)。标准库 std::complex 通过运算符重载,将原本需要显式调用的命名函数(如 add、is_equal)映射为了 +、==、+= 等运算符,使得自定义类型的对象能够像 int、double 等内置类型一样参与表达式运算,从而大幅提升了代码的可读性和自然度。

3.

(1)非必须。

如果声明为普通非成员函数(不用 friend):完全可以实现相同功能,但必须通过类的公有成员函数来间接访问数据。具体思路是:
    output:改用 value.real() 和 value.imag()。
    abs:改用 std::hypot(value.real(), value.imag())。
    add:改用 Complex(lhs.real() + rhs.real(), lhs.imag() + rhs.imag())。

(2)

没有。 std::abs(std::complex) 是一个非成员的函数模板,声明如下:

template< class T >
T abs( const complex<T>& z );

它并非 std::complex 类的友元。其实现通常是通过公有成员函数 z.real() 和 z.imag() 来计算模长(效果等价于 std::hypot(z.real(), z.imag())),因此不需要访问私有成员,自然也无需友元声明。

任务3:

代码组织:

  PlayerControl.h 播放控制类PlayerControl声明
  PlayerControl.cpp 播放控制类PlayerControl实现
  task3.cpp 测试模块 + main

PlayerControl.h

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

PlayerControl.cpp

 1 #include "PlayerControl.h"
 2 
 3 #include <algorithm>  
 4 #include <iostream>
 5 
 6 int PlayerControl::total_cnt = 0;
 7 
 8 PlayerControl::PlayerControl() {}
 9 
10 // 待补足
11 // 1. 将输入字符串统一成转为小写,实现大小写不敏感
12 // 2. 匹配"play"/"pause"/"next"/"prev"/"stop"并返回对应枚举;
13 //    未匹配的字符串返回ControlType::Unknown
14 ControlType PlayerControl::parse(const std::string& control_str) {
15     std::string s = control_str;
16     for (std::size_t i = 0; i < s.size(); ++i) {
17         if (s[i] >= 'A' && s[i] <= 'Z') {
18             s[i] = static_cast<char>(s[i] - 'A' + 'a');
19         }
20     }
21 
22     // 2. 依次匹配关键字,返回对应枚举
23     if (s == "play")  return ControlType::Play;
24     if (s == "pause") return ControlType::Pause;
25     if (s == "next")  return ControlType::Next;
26     if (s == "prev")  return ControlType::Prev;
27     if (s == "stop")  return ControlType::Stop;
28 
29     // 3. 未匹配
30     return ControlType::Unknown;
31 }
32 
33 void PlayerControl::execute(ControlType cmd) const {
34     // 每执行一次控制操作(含未知命令),total_cnt自增 1
35     ++total_cnt; 
36 
37     switch (cmd) {
38     case ControlType::Play:  std::cout << "[play] Playing music...\n"; break;
39     case ControlType::Pause: std::cout << "[Pause] Music paused\n";    break;
40     case ControlType::Next:  std::cout << "[Next] Skipping to next track\n"; break;
41     case ControlType::Prev:  std::cout << "[Prev] Back to previous track\n"; break;
42     case ControlType::Stop:  std::cout << "[Stop] Music stopped\n"; break;
43     default:                 std::cout << "[Error] unknown control\n"; break;
44     }
45 }
46 
47 int PlayerControl::get_cnt() {
48     return total_cnt;
49 }

task3.cpp

 1 #include <iostream>
 2 
 3 #include "PlayerControl.h"
 4 
 5 void test() {
 6     PlayerControl controller;
 7     std::string control_str;
 8     std::cout << "Enter Control: (play/pause/next/prev/stop/quit):\n";
 9 
10     while(std::cin >> control_str) {
11         if(control_str == "quit")
12             break;
13         
14         ControlType cmd = controller.parse(control_str);
15         controller.execute(cmd);
16         std::cout << "Current Player control: " << PlayerControl::get_cnt() << "\n\n";
17     }
18 }
19 
20 int main() {
21     test();
22 }

运行代码截图:

图片

观察与思考:

total_cnt 是一个静态成员变量,而 const 成员函数限制的是非静态成员变量的修改。

任务4:

代码组织:

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

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

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

Fraction.h

 1 #ifndef FRACTION_H
 2 #define FRACTION_H
 3 
 4 #include <string>
 5 
 6 class Fraction {
 7 public:
 8     static const std::string doc;
 9 
10     explicit Fraction(int up0);
11     Fraction(int up0, int down0);
12     Fraction(const Fraction&) = default;
13 
14     int get_up() const noexcept;
15     int get_down() const noexcept;
16     Fraction negative() const;
17 
18 private:
19     Fraction(long long up0, long long down0);
20 
21     int up;
22     int down;
23 
24     friend Fraction add(const Fraction& lhs, const Fraction& rhs);
25     friend Fraction sub(const Fraction& lhs, const Fraction& rhs);
26     friend Fraction mul(const Fraction& lhs, const Fraction& rhs);
27     friend Fraction div(const Fraction& lhs, const Fraction& rhs);
28 };
29 
30 void output(const Fraction& fraction);
31 Fraction add(const Fraction& lhs, const Fraction& rhs);
32 Fraction sub(const Fraction& lhs, const Fraction& rhs);
33 Fraction mul(const Fraction& lhs, const Fraction& rhs);
34 Fraction div(const Fraction& lhs, const Fraction& rhs);
35 
36 #endif

Fraction.cpp

 1 #include "Fraction.h"
 2 
 3 #include <iostream>
 4 #include <limits>
 5 #include <stdexcept>
 6 
 7 const std::string Fraction::doc = "Fraction类 v 0.01版.\n"
 8                                   "目前仅支持分数对象的构造、输出、加/减/乘/除运算.";
 9 
10 namespace {
11 
12 long long gcd(long long lhs, long long rhs) {
13     while (rhs != 0) {
14         const long long remainder = lhs % rhs;
15         lhs = rhs;
16         rhs = remainder;
17     }
18     return lhs;
19 }
20 
21 }  // namespace
22 
23 Fraction::Fraction(int up0) : Fraction(up0, 1) {}
24 
25 Fraction::Fraction(int up0, int down0)
26     : Fraction(static_cast<long long>(up0), static_cast<long long>(down0)) {}
27 
28 Fraction::Fraction(long long up0, long long down0) : up(0), down(1) {
29     if (down0 == 0) {
30         throw std::invalid_argument("Fraction: 分母不能为0");
31     }
32 
33     if (down0 < 0) {
34         up0 = -up0;
35         down0 = -down0;
36     }
37 
38     const long long divisor = gcd(up0 < 0 ? -up0 : up0, down0);
39     up0 /= divisor;
40     down0 /= divisor;
41 
42     if (up0 < std::numeric_limits<int>::min() ||
43         up0 > std::numeric_limits<int>::max() ||
44         down0 > std::numeric_limits<int>::max()) {
45         throw std::overflow_error("Fraction: 结果超出整数范围");
46     }
47 
48     up = static_cast<int>(up0);
49     down = static_cast<int>(down0);
50 }
51 
52 int Fraction::get_up() const noexcept {
53     return up;
54 }
55 
56 int Fraction::get_down() const noexcept {
57     return down;
58 }
59 
60 Fraction Fraction::negative() const {
61     return Fraction(-static_cast<long long>(up), static_cast<long long>(down));
62 }
63 
64 void output(const Fraction& fraction) {
65     std::cout << fraction.get_up() << '/' << fraction.get_down();
66 }
67 
68 Fraction add(const Fraction& lhs, const Fraction& rhs) {
69     return Fraction(static_cast<long long>(lhs.up) * rhs.down +
70                         static_cast<long long>(rhs.up) * lhs.down,
71                     static_cast<long long>(lhs.down) * rhs.down);
72 }
73 
74 Fraction sub(const Fraction& lhs, const Fraction& rhs) {
75     return Fraction(static_cast<long long>(lhs.up) * rhs.down -
76                         static_cast<long long>(rhs.up) * lhs.down,
77                     static_cast<long long>(lhs.down) * rhs.down);
78 }
79 
80 Fraction mul(const Fraction& lhs, const Fraction& rhs) {
81     return Fraction(static_cast<long long>(lhs.up) * rhs.up,
82                     static_cast<long long>(lhs.down) * rhs.down);
83 }
84 
85 Fraction div(const Fraction& lhs, const Fraction& rhs) {
86     if (rhs.up == 0) {
87         throw std::invalid_argument("Fraction: 不能除以0");
88     }
89 
90     return Fraction(static_cast<long long>(lhs.up) * rhs.down,
91                     static_cast<long long>(lhs.down) * rhs.up);
92 }

task4.cpp

#include <iostream>

#include "Fraction.h"

void test1() {
    using std::cout;
    using std::endl;   

    cout << "Fraction类测试: " << endl;
    cout << Fraction::doc << endl << endl;

    Fraction f1(5);
    Fraction f2(3, -4), f3(-18, 12);
    Fraction f4(f3);
    cout << "f1 = "; output(f1); cout << endl;
    cout << "f2 = "; output(f2); cout << endl;
    cout << "f3 = "; output(f3); cout << endl;
    cout << "f4 = "; output(f4); cout << endl;

    const Fraction f5(f4.negative());
    cout << "f5 = "; output(f5); cout << endl;
    cout << "f5.get_up() = " << f5.get_up() 
        << ", f5.get_down() = " << f5.get_down() << endl;

    cout << "f1 + f2 = "; output(add(f1, f2)); cout << endl;
    cout << "f1 - f2 = "; output(sub(f1, f2)); cout << endl;
    cout << "f1 * f2 = "; output(mul(f1, f2)); cout << endl;
    cout << "f1 / f2 = "; output(div(f1, f2)); cout << endl;
    cout << "f4 + f5 = "; output(add(f4, f5)); cout << endl;
}

void test2() {
    using std::cout;
    using std::endl;

    Fraction f6(42, 55), f7(0, 3);
    cout << "f6 = "; output(f6); cout << endl;
    cout << "f7 = "; output(f7); cout << endl;
    cout << "f6 / f7 = "; output(div(f6, f7)); cout << endl;
}

int main() {
    std::cout << "测试1: Fraction类基础功能测试\n";
    test1();

    std::cout << "\n测试2: 分母为0测试: \n";
    test2();
}

运行结果截图:

图片

观察与思考:

我选择的是方案1:分数类+友元函数

理由:

(1)直接访问私有数据,无需暴露额外接口:分数的加减乘除运算需要同时获取两个操作数(lhs 和 rhs)的分子和分母。通过友元函数,我们可以直接访问 up 和 down。如果采用方案2(非友元的命名空间自由函数),则必须依赖公共的 get_up() 和 get_down() 方法,这无疑增加了类的公共接口面积(API surface),破坏了封装性。
(2)性能与简洁性:直接访问内部成员比通过 getter 函数调用(即使 getter 可能被内联)在代码层面更简洁,且毫无性能损耗。对于核心的数学运算,直接在实现层操作数据更加高效。
(3)逻辑上的高内聚:加减乘除本质上是基于分数内部状态(分子、分母)的底层操作。它们与类的耦合度极高,将其作为友元函数,表明它们是该类不可分割的逻辑延伸。
(4)避免过度设计:方案2需要额外引入命名空间(例如 namespace FractionOps)来防止全局命名空间污染。虽然这是一个好习惯,但对于当前这种强关联的数学运算,友元函数配合类本身的接口已经足够清晰。

posted @ 2026-11-18 14:04  Salt~  阅读(6)  评论(0)    收藏  举报