实验2
四.实验结论
1.实验任务1
t.h源代码:
#pragma once #include <string> class T { public: T(int x = 0, int y = 0); // 普通构造函数 T(const T &t); // 复制构造函数 T(T &&t); // 移动构造函数 ~T(); // 析构函数 void adjust(int ratio); // 按系数成倍调整数据 static int get_cnt(); // 显示当前T类对象总数 friend void output(const T &t); // 友元, 以(m1, m2)形式输出对象t static const std::string doc; // 类T的描述信息 static const int MAX_CNT; // 类T对象上限 private: int m1, m2; // 对象数据成员 static int current_cnt; // 当前T类对象数目 };
t.cpp源代码:
#include "t.h" #include <iostream> #include <stdexcept> #include <string> // static成员数据: 类内声明、类外初始化 const std::string T::doc{"a simple class sample"}; const int T::MAX_CNT = 999; int T::current_cnt = 0; // 对象方法 T::T(int x, int y): m1{x}, m2{y} { if(current_cnt == MAX_CNT) { throw std::runtime_error("T: maximum object count exceeded"); } ++current_cnt; std::cout << "T constructor called.\n"; } T::T(const T &t): m1{t.m1}, m2{t.m2} { if(current_cnt == MAX_CNT) { throw std::runtime_error("T: maximum object count exceeded"); } ++current_cnt; std::cout << "T copy constructor called.\n"; } T::T(T &&t): m1{t.m1}, m2{t.m2} { if(current_cnt == MAX_CNT) { throw std::runtime_error("T: maximum object count exceeded"); } ++current_cnt; std::cout << "T move constructor called.\n"; } T::~T() { --current_cnt; std::cout << "T destructor called.\n"; } void T::adjust(int ratio) { m1 *= ratio; m2 *= ratio; } // 类方法 int T::get_cnt() { return current_cnt; } // 友元 void output(const T &t) { std::cout << "(" << t.m1 << ", " << t.m2 << ")"; }
task1.cpp源代码:
#include <iostream> #include <utility> #include "t.h" void test() { using std::cout; using std::endl; cout << "T info: " << T::doc << endl; cout << "T objects'max count: " << T::MAX_CNT << endl; cout << "T objects'current count: " << T::get_cnt() << endl << endl; { T t1; cout << "t1 = "; output(t1); cout << endl; T t2(3, 4); cout << "t2 = "; output(t2); cout << endl; T t3(t2); t3.adjust(2); cout << "t3 = "; output(t3); cout << endl; T t4(std::move(t2)); cout << "t4 = "; output(t4); cout << endl; cout << "test: T objects'current count: " << T::get_cnt() << endl; } cout << "test: T objects'current count: " << T::get_cnt() << endl; } int main() { std::cout << "test Class T: \n"; test(); }
运行测试截图:

问题1:
普通构造函数 T(int x = 0, int y = 0):新建对象时给成员变量赋初值,用类名直接定义对象时触发。复制构造函数 T(const T &t):拿一个已经存在的对象,复制出一个一模一样的新对象,用一个对象去初始化另一个同类型对象时触发。移动构造函数 T(T &&t):把别人对象里的数据 "搬" 过来,当传入的是右值、或用了 std::move 时触发。析构函数 ~T():对象离开作用域、被销毁时自动调用,做清理工作。
t1触发了普通构造函数,t2也触发了普通构造函数,t3触发了复制构造函数,t4触发了移动构造函数。
问题2:
不能正常编译。
报错截图:

像 int T::current_cnt = 0; 这种静态成员,属于整个类,整个程序里只应该有一份定义。把头文件放进 t.h 后,t.cpp 和 task1.cpp 都包含了 t.h,等于每个文件都生成了一份定义,链接时就会报 multiple definition之类的错。所以静态成员的类外初始化规范做法就是放在 .cpp 里,而不是头文件里。
问题3:
t1、t2、t3、t4 都定义在 test() 函数里面那个 { } 中:进去时构造,出去时就全部销毁,离开之后对象就不存在了。
在这个作用域里,不能通过 t1 直接访问它的私有成员 m1、m2,编译器会报错。这体现了类的封装特性,就是私有成员只对类自己内部开放,外面不能随便碰。
问题4:
throw 是用来抛出异常的:当对象数量达到上限再新建对象时,程序就主动抛一个 runtime_error,告诉外面 "对象个数超了",而不是硬着头皮继续创建。
崩溃了。
运行结果截图:
已经创建出来的 t1、t2 不会被正常销毁,它们的析构函数不会被调用,因为正常销毁是在对象离开作用域时才发生的,这里异常直接把程序带走了,既没走到作用域结束,也没有 catch 块来做栈上清理,所以析构没机会执行。
实验任务2:
Complex.h源代码:
#pragma once #include <string> class Complex { public: static const std::string doc; Complex(double r = 0, double i = 0); Complex(const Complex& other); double real() const; double imag() const; void add(const Complex& other); friend void output(const Complex& c); friend double abs(const Complex& c); friend Complex add(const Complex& a, const Complex& b); friend bool is_equal(const Complex& a, const Complex& b); friend bool is_not_equal(const Complex& a, const Complex& b); private: double real_; double imag_; };
Complex.cpp源代码:
#include "Complex.h" #include <cmath> #include <iostream> const std::string Complex::doc{"a simplified complex class"}; Complex::Complex(double r, double i) : real_{r}, imag_{i} {} Complex::Complex(const Complex& other) : real_{other.real_}, imag_{other.imag_} {} double Complex::real() const { return real_; } double Complex::imag() const { return imag_; } void Complex::add(const Complex& other) { real_ += other.real_; imag_ += other.imag_; } void output(const Complex& c) { std::cout << c.real_; if (c.imag_ >= 0) { std::cout << " + " << c.imag_ << "i"; } else { std::cout << " - " << -c.imag_ << "i"; } } double abs(const Complex& c) { return std::sqrt(c.real_ * c.real_ + c.imag_ * c.imag_); } Complex add(const Complex& a, const Complex& b) { return Complex(a.real_ + b.real_, a.imag_ + b.imag_); } bool is_equal(const Complex& a, const Complex& b) { return a.real_ == b.real_ && a.imag_ == b.imag_; } bool is_not_equal(const Complex& a, const Complex& b) { return !is_equal(a, b); }
task2.cpp源代码:
#include <iomanip> #include <iostream> #include <complex> #include "Complex.h" // 测试自定义类Complex void test_Complex() { using std::cout; using std::endl; using std::boolalpha; cout << "类成员测试: " << endl; cout << Complex::doc << endl << endl; cout << "Complex对象测试: " << endl; Complex c1; Complex c2(3, -4); Complex c3(c2); Complex c4 = c2; const Complex c5(3.5); const Complex c6 = 3.5; cout << "c1 = "; output(c1); cout << endl; cout << "c2 = "; output(c2); cout << endl; cout << "c3 = "; output(c3); cout << endl; cout << "c4 = "; output(c4); cout << endl; cout << "c5 = "; output(c5); cout << endl; cout << "c6.real = " << c6.real() << ", c6.imag = " << c6.imag() << endl << endl; cout << "复数运算测试: " << endl; cout << "abs(c2) = " << abs(c2) << endl; c1.add(c2); cout << "c1 += c2, c1 = "; output(c1); cout << endl; cout << boolalpha; cout << "c1 == c2 : " << is_equal(c1, c2) << endl; cout << "c1 != c2 : " << is_not_equal(c1, c2) << endl; c4 = add(c2, c3); cout << "c4 = c2 + c3, c4 = "; output(c4); cout << endl; } // 测试标准库类模板complex void test_std_complex() { using std::cout; using std::endl; using std::boolalpha; cout << "std::complex<double>对象测试: " << endl; std::complex<double> c1; std::complex<double> c2(3, -4); std::complex<double> c3(c2); std::complex<double> c4 = c2; std::complex<double> c5 = 3.5; const std::complex<double> c6(3.5); cout << "c1 = " << c1 << endl; cout << "c2 = " << c2 << endl; cout << "c3 = " << c3 << endl; cout << "c4 = " << c4 << endl; cout << "c5 = " << c5 << endl; cout << "c6.real = " << c6.real() << ", c6.imag = " << c6.imag() << endl << endl; cout << "复数运算测试: " << endl; cout << "abs(c2) = " << abs(c2) << endl; c1 += c2; cout << "c1 += c2, c1 = " << c1 << endl; cout << boolalpha; cout << "c1 == c2 : " << (c1 == c2)<< endl; cout << "c1 != c2 : " << (c1 != c2) << endl; c4 = c2 + c3; cout << "c4 = c2 + c3, c4 = " << c4 << endl; } int main() { std::cout << "*******测试1: 自定义类Complex*******\n"; test_Complex(); std::cout << "\n*******测试2: 标准库类模板complex*******\n"; test_std_complex(); }
运行测试截图:

问题1:
① 成员函数后面要加 const,也就是 const 成员函数。如果不加,编译器会报错,因为const 对象不能调用非 const 成员函数。
②不能。c6 是 const 对象,初始化之后就不允许再改了,而 add() 会修改对象自身,是个非 const 成员函数,const 对象不能调它。这体现了 const 保护机制,const 对象是只读的,防止被意外改掉。
问题2:
标准库 std::complex 的用法更简洁,直接用 +=、+、==、!=这些运算符就行,不用记一堆函数名。
能看出来函数和运算符其实本质上是一回事,运算符只是一种写起来更直观的特殊函数。标准库把让代码读起来更贴近数学写法。
问题3:
①不是必须的。也可以把它们写成普通的非成员函数,不用 friend。思路是,在类里把取实部、虚部的接口设成公有的,外部函数通过这些公有接口拿到数据再做计算,只是不能直接碰私有成员。
③ 我觉得 friend 只在确实需要直接访问私有成员、又不方便做成成员函数的时候才用,比如运算符要支持左右两边对称转换。能用公有接口解决的就别用 friend,因为友元会把内部细节暴露出去,破坏封装,后期改起来更麻烦。
实验任务3:
PlayerControl.h源代码:
#pragma once #include <string> enum class ControlType {Play, Pause, Next, Prev, Stop, Unknown}; class PlayerControl { public: PlayerControl(); ControlType parse(const std::string& control_str); // 实现std::string --> ControlType转换 void execute(ControlType cmd) const; // 执行控制操作(以打印输出模拟) static int get_cnt(); private: static int total_cnt; };
PlayerControl.cpp源代码:
#include "PlayerControl.h" #include <cctype> #include <algorithm> #include <iostream> int PlayerControl::total_cnt = 0; PlayerControl::PlayerControl() {} // 待补足 // 1. 将输入字符串统一成转为小写,实现大小写不敏感 // 2. 匹配"play"/"pause"/"next"/"prev"/"stop"并返回对应枚举; // 未匹配的字符串返回ControlType::Unknown ControlType PlayerControl::parse(const std::string& control_str) { std::string s; for (char ch : control_str) { s += static_cast<char>(tolower(static_cast<unsigned char>(ch))); } if (s == "play") return ControlType::Play; if (s == "pause") return ControlType::Pause; if (s == "next") return ControlType::Next; if (s == "prev") return ControlType::Prev; if (s == "stop") return ControlType::Stop; return ControlType::Unknown; } void PlayerControl::execute(ControlType cmd) const { // 每执行一次控制操作(含未知命令),total_cnt自增 1 ++total_cnt; switch (cmd) { case ControlType::Play: std::cout << "[play] Playing music...\n"; break; case ControlType::Pause: std::cout << "[Pause] Music paused\n"; break; case ControlType::Next: std::cout << "[Next] Skipping to next track\n"; break; case ControlType::Prev: std::cout << "[Prev] Back to previous track\n"; break; case ControlType::Stop: std::cout << "[Stop] Music stopped\n"; break; default: std::cout << "[Error] unknown control\n"; break; } } int PlayerControl::get_cnt() { return total_cnt; }
task3.cpp源代码:
#include <iostream> #include "PlayerControl.h" void test() { PlayerControl controller; std::string control_str; std::cout << "Enter Control: (play/pause/next/prev/stop/quit):\n"; while(std::cin >> control_str) { if(control_str == "quit") break; ControlType cmd = controller.parse(control_str); controller.execute(cmd); std::cout << "Current Player control: " << PlayerControl::get_cnt() << "\n\n"; } } int main() { test(); }
运行测试截图:

问题回答:
因为 total_cnt 是 static 静态成员,它属于整个类、所有对象共用,不属于某一个具体对象。const 修饰的是当前这个对象,限制的是不能改它自己的非静态成员,静态成员不在这个约束范围内。
实验任务4:
Fraction.h源代码:
#pragma once #include <string> class Fraction { public: static const std::string doc; Fraction(int up0); Fraction(int up0, int down0); Fraction(const Fraction& other); int get_up() const; int get_down() const; Fraction negative() const; friend void output(const Fraction& f); friend Fraction add(const Fraction& a, const Fraction& b); friend Fraction sub(const Fraction& a, const Fraction& b); friend Fraction mul(const Fraction& a, const Fraction& b); friend Fraction div(const Fraction& a, const Fraction& b); private: int up; int down; };
Fraction.cpp源代码:
#include "Fraction.h" #include <iostream> #include <stdexcept> namespace { int gcd(int a, int b) { a = a < 0 ? -a : a; b = b < 0 ? -b : b; while (b != 0) { int r = a % b; a = b; b = r; } return a; } } const std::string Fraction::doc{ "Fraction类 v 0.01 版.\n目前仅支持分数对象的构造、输出、加/减/乘/除运算."}; Fraction::Fraction(int up0) : up{up0}, down{1} {} Fraction::Fraction(int up0, int down0) { if (down0 == 0) { throw std::invalid_argument("Fraction: 分母不能为0"); } int g = gcd(up0, down0); up = up0 / g; down = down0 / g; if (down < 0) { up = -up; down = -down; } } Fraction::Fraction(const Fraction& other) : up{other.up}, down{other.down} {} int Fraction::get_up() const { return up; } int Fraction::get_down() const { return down; } Fraction Fraction::negative() const { return Fraction(-up, down); } void output(const Fraction& f) { if (f.down == 1 || f.up == 0) { std::cout << f.up; } else { std::cout << f.up << "/" << f.down; } } Fraction add(const Fraction& a, const Fraction& b) { return Fraction(a.up * b.down + b.up * a.down, a.down * b.down); } Fraction sub(const Fraction& a, const Fraction& b) { return Fraction(a.up * b.down - b.up * a.down, a.down * b.down); } Fraction mul(const Fraction& a, const Fraction& b) { return Fraction(a.up * b.up, a.down * b.down); } Fraction div(const Fraction& a, const Fraction& b) { return Fraction(a.up * b.down, a.down * b.up); }
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:分数类 + 友元函数。
理由:测试代码里 output、add、sub、mul、div 本来就是按自由函数的形式调用的,用友元可以直接访问分子 up 和分母 down,做通分、约分这些计算时写起来更顺手
五.实验总结
这次实验把类和对象从头走了一遍:从写类的声明、成员实现,到单独写测试文件跑通,算是对面向对象有了个直观感受。几个点印象比较深:构造函数和析构函数什么时候被调用,以前只看书上写,这次靠输出一行行看构造、析构的顺序才真正搞明白;静态成员是整个类共用的,不属于某个对象,还有就是友元可以直接访问私有成员,但会破坏一点封装,然后const 对象只能调 const 成员函数,想改它是不行的。多文件结构也练了,头文件放声明、cpp 放实现,最后几个 cpp 一起编译链接。

浙公网安备 33010602011771号