OOP 实验2
实验2 类和对象_基础编程1
任务1
- 源代码t.cpp
点击查看代码
//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 << ")";
}
- 源代码t.h
点击查看代码
//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类对象数目
};
- 源代码Task1.cpp
点击查看代码
//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();
}
- 测试截图

-
回答问题
Q1:t.h中,line7-10给出了各种构造函数、析构函数。用文字简洁说明它们各自的功能、调用时机。结合t1-t4,说明它们分别触发了哪个构造函数。
a1:
普通构造函数T(int x = 0, int y = 0); :用给出的值初始化m1,m2,并且让计数的变量current_cnt++。它仅仅在创建普通的对象的时候调用。
复制构造函数T(const T &t);:用已经有的对象t来复制m1,m2,并且让计数的变量current_cnt++。它是在用同类型对象初始化新对象(也可以说是复制吧)的时候调用的。
移动构造函数T(T &&t);:用临时对象或用标准库里的std::move转移数据。顾名思义是在移动构造的时候调用。
析构函数~T():释放空间,用于释放对象所占的内存及完成相关的"清理"工作。它是在对象生存期结束时由编译器自动调用的。
由程序运行结果可知
t1触发了普通构造函数T(int x = 0, int y = 0);并且调用了默认值x=0,y=0。
t2触发了普通构造函数T(int x = 0, int y = 0);并且给出了值x=3,y=4。
t3触发了复制构造函数(用t2复制)。
t4触发了移动构造函数。
在t1~t4生命周期结束的时候分别调用了一次析构函数。Q2:t.cpp中,line8-10,剪切到t.h的末尾,重新编译,程序能否正确编译。如不能,以截图形式给出报错信息,分析原因。
a2:可以正确编译。
![t1-02]()
Q3:类T的测试模块 test 中,说明对象 t1-t4 的作用域和生命期。并思考:在这个作用域内,能否通过 t1 访问其私有成员 m1、m2?这体现了类的什么特性?
a3:作用域:t1~t4 定义在 test() 函数的内部 {} 块中,作用域从声明点的地方到右半大括号“}”结束。生命期:从函数构造成功开始,到调用析构函数结束。在这个作用域内,不可以通过t1访问其私有成员m1、m2,因为明确规定它们属于private私有成员。体现了封装的特性,把内部数据变成私有的,有且仅有通过特定方式(友元函数、类内的成员函数)访问。Q4:t.cpp中包含了头文件 #include
,构造函数中均使用了以下代码。使用搜索引擎/AI查询 throw功能。把t.cpp中T::MAX_CNT值改成2,重新编译、运行程序。观察输出,程序是正常结束还是崩溃了?给出截图运行结果。
如果崩溃了,已经创建的对象(如t1),会被正常销毁吗?给出答案,并说明理由。
a4:throw 功能的AI解答:抛出异常,用于错误处理。当 current_cnt == MAX_CNT 时抛出std::runtime_error,阻止对象继续创建。
在把t.cpp中T::MAX_CNT值改成2后,程序可以正常编译,但是在创建第3个对象(如 t3)时,构造函数抛出 std::runtime_error,程序崩溃终止(运行结果如下图)

任务2
- 源代码Complex.cpp
点击查看代码
#include "Complex.h"
#include <cmath> // cmath提供sqrt函数
#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_;
}
// 将 other 的实部虚部加到自身
void Complex::add(const Complex& other) {
real_ += other.real_;
imag_ += other.imag_;
}
//友元函数
// 输出复数:格式为 a+bi 或 a-bi
void output(const Complex& c) {
if (c.imag_ >= 0) {
std::cout << c.real_ << "+" << c.imag_ << "i";
} else {
// 虚部为负时,输出 a-bi(如 3-4i)
std::cout << c.real_ << "-" << -c.imag_ << "i";
}
}
// 取模:sqrt(real2 + imag2)
double abs(const Complex& c) {
return std::sqrt(c.real_ * c.real_ + c.imag_ * c.imag_);
}
// 两个复数相加,返回新对象
Complex add(const Complex& c1, const Complex& c2) {
return Complex(c1.real_ + c2.real_, c1.imag_ + c2.imag_);
}
// 判断两个复数是否相等(实部虚部都相等)
bool is_equal(const Complex& c1, const Complex& c2) {
return (c1.real_ == c2.real_) && (c1.imag_ == c2.imag_);
}
// 判断两个复数是否不相等
bool is_not_equal(const Complex& c1, const Complex& c2) {
return !is_equal(c1, c2);//实验课上讲的,可以直接返回! is_equal(c1, c2);
}
- 源代码Complex.h
点击查看代码
#include <string>
#include <iostream>
class Complex {
public:
//类属性
static const std::string doc; // 类说明,公有、常量、静态
//构造函数
Complex(double r = 0.0, double i = 0.0); // 默认构造
Complex(const Complex& other); // 复制构造
//对象接口部分(须是 const 成员函数)
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& c1, const Complex& c2); // 两复数相加
friend bool is_equal(const Complex& c1, const Complex& c2); // 相等判断
friend bool is_not_equal(const Complex& c1, const Complex& c2); // 不等判断
private:
//私有对象属性
double real_; // 实部
double imag_; // 虚部
};
- 源代码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();
}
- 测试截图

-
回答问题
Q1:在测试代码中,c6是cons对象。
① 为了让 c6.real() 和 c6.imag() 能编译通过,在设计 Complex 类的成员函数时,必须加上什么关键字?如果不加,编译器会报什么错?(请简述或截图报错信息)
② 作为const对象,c6在初始化后允许再被修改。在测试代码中添加执行 c6.add(c2); ,能编译通过吗?为什么?这体现了类的什么保护机制?
a1:①必须加 const 关键字,将成员函数声明为:double real() const; 和 double imag() const;,如果不加,报错be like↓(见报错图片)
![t2-01-no const]()
②不能编译通过,add成员函数本来不是const的,但是c6却是const对象,它不可以调用任何可能修改自身的非const成员函数。也就是我们课上俗称的“权限变大了就会报错”。
体现的保护机制:const对象保护机制。它确保const对象在生命周期内不会被意外修改。
![t2-01-error]()
Q2:比较自定义类 Complex 和标准库模板类 complex 的用法,在使用形式上,哪种更简洁?据此推断函数和运算是否存在内在关联呢?
a2:我认为标准库std::complex更简洁,因为它直接使用了运算符(+, +=, ==, !=, << 等),让复数运算可以像正常书写一样来运算。关联:普通函数可以通过一些方式转化为运算形式,让我们使用更加便利。Q3:① 本练习中, output 、 abs 、 add (非成员版本)等被设为Complex的友元。这是必须的吗?如果将其声明为普通非成员函数(不用 friend ),能否实现相同的功能?简述思路。
② 标准库 std::complex 是否把 abs 设为友元?(查阅 cppreference后回答,并提供页面具体链接地址)
③ 工业场景中,什么时候才考虑使用 friend ?和AI讨论后,简洁概括你的思考和结论。(限150字内)
a3:①不是必须的。不用friend也能实现:主要是因为类中已经提供了公有的real() 和imag() 接口,普通非成员函数可以通过这些接口获取实部虚部,然后来完成输出、取模、相加等操作。解决思路:把output、abs、add写成普通函数(不设置友元函数friend),在函数体内调用c.real() 和 c.imag() 来获取数据。
② 没有。std::abs 是一个普通的非成员函数模板,它通过调用 std::complex 的公有成员函数 real() 和 imag() 来计算模长,而不是友元。(cppreference见下↓)
![t2-03-cppreference]()
③尽管友元函数非常方便,但是它破坏封装,会降低可测试性和可维护性。工业场景中,friend友元函数应谨慎使用(在这些方面):运算符重载需要访问私有成员、或者两个类紧密耦合,需要共享内部状态。
核心原则是说:优先用公有接口,友元是最后手段,因为它破坏封装,增加耦合,降低可维护性。
任务3
- 源代码PlayerControl.cpp
点击查看代码
#include "PlayerControl.h"
#include <algorithm>
#include <iostream>
int PlayerControl::total_cnt = 0;
PlayerControl::PlayerControl() {}
// 将输入字符串统一成转为小写的函数
std::string to_lower(const std::string& s) {
std::string lower_s = s;
for (char& c : lower_s) {
c = std::tolower(c);
}
return lower_s;
}
ControlType PlayerControl::parse(const std::string& control_str) {
// 1. 先将输入统一转为小写
std::string lower_str = to_lower(control_str);
// 2. 后匹配"play"/"pause"/"next"/"prev"/"stop"并返回对应枚举;
if (lower_str == "play") {
return ControlType::Play;
} else if (lower_str == "pause") {
return ControlType::Pause;
} else if (lower_str == "next") {
return ControlType::Next;
} else if (lower_str == "prev") {
return ControlType::Prev;
} else if (lower_str == "stop") {
return ControlType::Stop;
} else {
return ControlType::Unknown; // 未匹配的字符串返回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;
}
- 源代码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;
};
- 源代码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();
}
- 测试截图

- 回答问题
Q:接口 void execute(ControlType cmd) const; 是const成员函数,为什么在其内部实现允许代码++total_cnt?
a:对于total_cnt,它是一个static(静态的)成员变量,在PlayerControl.h文件,类PlayerControl的声明里“private:static int total_cnt;”,明确的强调了total_cnt是属于类的本身。
关于const成员函数的限制,因为本打算前面翻阅“第2讲_cplus语言基础_1”以及“第4讲_类和对象的两小讲”pdf文档发现没有找到更具体的说明,故咨询了一下ai:const 成员函数的限制是不能修改调用该函数的对象实例的非静态成员变量(即不能修改 *this 所指向的对象状态)。因为静态成员变量不属于任何对象实例,修改它不会破坏某个具体对象的常量性,所以 const 成员函数可以修改静态成员变量。
实验4
- Fraction..h
点击查看代码
#pragma once
#include <string>
#include <iostream>
class Fraction {
public:
static const std::string doc;
Fraction(int up = 0, int down = 1);
Fraction(const Fraction& other);
int get_up() const;
int get_down() const;
Fraction negative() const;
private:
int up_;
int down_;
void normalize();
};
//命名空间 frac
namespace frac {
void output(const Fraction& f);
Fraction add(const Fraction& f1, const Fraction& f2);
Fraction sub(const Fraction& f1, const Fraction& f2);
Fraction mul(const Fraction& f1, const Fraction& f2);
Fraction div(const Fraction& f1, const Fraction& f2);
}
- Fraction..cpp
点击查看代码
#include "Fraction.h"
#include <stdexcept>
#include <cmath>
const std::string Fraction::doc = "Fraction类11.18版"; // 静态成员类外初始化
// 构造函数
Fraction::Fraction(int up, int down) : up_(up), down_(down) {
normalize();
}
// 复制构造
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 Fraction::normalize() {
if (down_ == 0) {
throw std::runtime_error("分母不能为0!");//分母非零检查
}
int a = std::abs(up_);
int b = std::abs(down_);
while (b != 0) { int t = a % b; a = b; b = t; } // 约分
if (a > 0) { up_ /= a; down_ /= a; }
// 负号归位:分母始终为正
if (down_ < 0) { up_ = -up_; down_ = -down_; }
}
// frac 命名空间函数实现
namespace frac {
void output(const Fraction& f) {
if (f.get_down() == 1) {
// 所有整除的情况,避免出现写代码第一次测试输出"5/1,0/1" : )
std::cout << f.get_up();
} else {
std::cout << f.get_up() << "/" << f.get_down();
}
}
Fraction add(const Fraction& f1, const Fraction& f2) {
return Fraction(
f1.get_up() * f2.get_down() + f2.get_up() * f1.get_down(),
f1.get_down() * f2.get_down()
);
}
Fraction sub(const Fraction& f1, const Fraction& f2) {
return Fraction(
f1.get_up() * f2.get_down() - f2.get_up() * f1.get_down(),
f1.get_down() * f2.get_down()
);
}
Fraction mul(const Fraction& f1, const Fraction& f2) {
return Fraction(
f1.get_up() * f2.get_up(),
f1.get_down() * f2.get_down()
);
}
Fraction div(const Fraction& f1, const Fraction& f2) {
return Fraction(
f1.get_up() * f2.get_down(),
f1.get_down() * f2.get_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 = "; frac::output(f1); cout << endl;
cout << "f2 = "; frac::output(f2); cout << endl;
cout << "f3 = "; frac::output(f3); cout << endl;
cout << "f4 = "; frac::output(f4); cout << endl;
const Fraction f5(f4.negative());
cout << "f5 = "; frac::output(f5); cout << endl;
cout << "f5.get_up() = " << f5.get_up()
<< ", f5.get_down() = " << f5.get_down() << endl;
cout << "f1 + f2 = "; frac::output(frac::add(f1, f2)); cout << endl;
cout << "f1 - f2 = "; frac::output(frac::sub(f1, f2)); cout << endl;
cout << "f1 * f2 = "; frac::output(frac::mul(f1, f2)); cout << endl;
cout << "f1 / f2 = "; frac::output(frac::div(f1, f2)); cout << endl;
cout << "f4 + f5 = "; frac::output(frac::add(f4, f5)); cout << endl;
}
void test2() {
using std::cout;
using std::endl;
Fraction f6(42, 55), f7(0, 3);
cout << "f6 = "; frac::output(f6); cout << endl;
cout << "f7 = "; frac::output(f7); cout << endl;
cout << "f6 / f7 = "; frac::output(frac::div(f6, f7)); cout << endl;
}
int main() {
std::cout << "测试1: Fraction类基础功能测试\n";
test1();
std::cout << "\n测试2: 分母为0测试: \n";
test2();
}
- 测试截图

- 回答问题
Q:分数运算( output/add/sub/mul/div ),你选择的是哪种设计方案?你的决策理由?
方案1:分数类 + 友元函数
方案2:分数类 + 命名空间自由函数
a:我选择了方案2:分数类 + 命名空间自由函数。前面任务2也说了,尽管友元函数非常方便,但是它破坏封装,会降低可测试性和可维护性。所以友元函数还是谨慎使用为好。另外就是,区分开命名空间可以避免命名冲突。(查阅5-1讲课件/配套课件所得)
实验总结
关于最后task4退出码3的一个真实反应,最后跑代码其实看到Process exited after 4.601 seconds with return value 3愣了一下,后来反应过来div(f6, f7) 触发了除以 0 且未被捕获的异常,老实说throw std::runtime_error这一段代码上课时候还是有点懵懵懂懂的。





浙公网安备 33010602011771号