实验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.h中,line7-10给出了各种构造函数、析构函数。用文字简洁说明它们各自的功能,调用时机。结合t1-t4,说明它们分别触发了哪个构造函数。
![image]()
(1)普通构造函数:用来初始化对象,可选择传参或不传参,可设置默认值,在对象被创建时调用。
(2)复制构造函数:将已经存在的同类型的对象的成员属性的值传给新建的对象,用已有的对象初始化新对象。
(3)移动构造函数:不复制资源,直接把源对象的资源所有权转移给新对象,然后把源对象置为空。
(4)析构函数:对象生命周期结束时自动调用,释放对象持有的资源,防止内存泄漏。
- 2、t.cpp中,line8-10,剪切到t.h的末尾,重新编译,程序能否正确编译。如不能,以截图形式给出报错信息,分析原因。
![image]()
不能,报错信息如下
报错显示了重复定义,这违反了C++的单一定义原则,因为变量是在头文件中所定义,且被t.cpp与task1.cpp同时定义了一次,所以编译错误。
- 3、类T的测试模块test中,说明对象t1-t4的作用域和生命期。并思考:在这个作用域内,能否通过t1访问其私有成员m1、m2?这体现了类的什么特性?
作用域为test()函数内,test()函数运行完对象就会调用析构函数被销毁。
不能通过t1访问其私有成员,这体现了类的封装与访问控制。
- 4、t.cpp中包含了头文件#include
,构造函数中均使用了以下代码。使用搜索引擎/AI查询throw功能。把t.cpp中T::MAX_CNT值改成2,重新编译、运行程序。观察输出,程序是正常结束还是崩溃了?给出截图运行结果。如果崩溃了,已经创建的对象(如t1),会被正常销毁吗?给出答案,并说明理由
抛出异常,主动中断正常执行流,把异常对象交给上层的
catch处理。
语法:throw 异常值;
程序会崩溃
t1,t2会被正常销毁,在出现异常时,析构函数依然会调用,在异常结果报告出来前将其正常销毁,避免内存的占用。
2.实验任务2
#include<iostream>
#include<string>
class Complex{
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_val;
double imag_val;
public:
static const std::string doc;
Complex();
Complex(double r);
Complex(double r, double i);
Complex(const Complex& other);
double real() const;
double imag() const;
void add(const Complex& other);
};
#include"Complex.h"
#include<iostream>
#include<cmath>
using namespace std;
const string Complex::doc = "a simplified Complex class";
Complex::Complex() : real_val(0), imag_val(0) {}
Complex::Complex(double r) : real_val(r), imag_val(0) {}
Complex::Complex(double r, double i) : real_val(r), imag_val(i) {}
Complex::Complex(const Complex& other)
{
real_val = other.real_val;
imag_val = other.imag_val;
}
double Complex::real() const
{
return real_val;
}
double Complex::imag() const
{
return imag_val;
}
void Complex::add(const Complex& other)
{
real_val += other.real_val;
imag_val += other.imag_val;
}
void output(const Complex& c)
{
cout << c.real_val << " + " << c.imag_val << "i";
}
double abs(const Complex& c)
{
return sqrt(c.real_val * c.real_val + c.imag_val * c.imag_val);
}
Complex add(const Complex& a, const Complex& b)
{
return Complex(a.real_val + b.real_val, a.imag_val + b.imag_val);
}
bool is_equal(const Complex& a, const Complex& b)
{
return a.real_val == b.real_val && a.imag_val == b.imag_val;
}
bool is_not_equal(const Complex& a, const Complex& b)
{
return !is_equal(a, b);
}
#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
① 为了让 c6.real() 和 c6.imag() 能编译通过,在设计 Complex 类的成员函数时,必须加上什么关键字?如果不加,编译器会报什么错?(请简述或截图报错信息)。
② 作为const对象,c6在初始化后允许再被修改。在测试代码中添加执行 c6.add(c2); ,能编译通过吗?为什么?这体现了类的什么保护机制?
成员函数 real() 和 imag() 声明/定义时,必须在函数签名末尾加 const
不能。 add(const Complex& other) 是非 const 成员函数,会修改对象本身(real_val += ...)。const对象初始化后不允许被修改,所以 c6.add(c2) 编译失败.这体现的是类的 const 正确性(constcorrectness)保护机制:编译器在编译期就拦截了「通过 const 对象修改其内部状态」的行为,保证被声明为 const 的对象在整个生命周期内不变。
- 问题2
比较自定义类 Complex 和标准库模板类 complex 的用法,在使用形式上,哪种更简洁?据此推断函数和运算是
否存在内在关联呢?
标准库 std::complex 更简洁、更自然,因为它把运算都做成了运算符重载,写起来接近数学表达式。
函数与运算确实存在内在关联:在 C++ 里,运算符本质上就是「名字比较特殊、语法比较简洁的函数」。
- 问题3
① 本练习中, output 、 abs 、 add (非成员版本)等被设为Complex的友元。这是必须的吗?如果将其声明为普通非成员函数(不用 friend ),能否实现相同的功能?简述思路。
不是必须的。不用 friend 的思路就是:改走公有接口.只要用 real()/imag() 这些公有接口就能拿到数据,完全不需要 friend,功能一致。friend只是让它们能绕开公有接口、直接读私有成员而已。
② 标准库 std::complex 是否把 abs 设为友元?(查阅 cppreference后回答,并提供页面具体链接地址)
不是。 std::abs 是一个普通的自由函数模板:
template< class T >
T abs( const std::complex& z );
它并不访问 std::complex 的私有成员,而是通过公有接口 z.real()、z.imag() 来计算(√(re² + im²)),所以无需设为 friend。
cppreference 页面链接: https://en.cppreference.com/w/cpp/numeric/complex/abs
③ 工业场景中,什么时候才考虑使用 friend ?和AI讨论后,简洁概括你的思考和结论。(限150字内)
仅当某函数必须访问类的私有成员,而把它做成公有接口会破坏封装或设计时才用 friend。典型场景:需要读私有数据、或两个类之间需要双向访问内部实现。绝大多数情况应优先用公有 getter/setter,friend能不用就不用,因为它与封装原则相悖,会放大耦合面。
3.实验任务3
#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;
};
include "PlayerControl.h"
include
include
int PlayerControl::total_cnt = 0;
PlayerControl::PlayerControl() {}
ControlType PlayerControl::parse(const std::string& control_str) {
std::string s = control_str;
// 1. 统一转小写,实现大小写不敏感
std::transform(s.begin(), s.end(), s.begin(),
[](unsigned char c) { return std::tolower(c); });
// 2. 匹配并返回对应枚举;未匹配返回 Unknown
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;
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;
}
#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();
return 0;
}
- 接口 void execute(ControlType cmd) const; 是const成员函数,为什么在其内部实现允许代码
++total_cnt ?
:const 成员函数限制的是「不能修改当前对象的非静态成员状态」;而 static
数据成员不属于任何具体对象,是类级别共享的,所以 const 成员函数可以修改它。
4.实验任务4
#pragma once
#include <string>
class Fraction {
public:
// 类属性:类说明(常量,公有)
static const std::string doc;
// 构造函数
Fraction(); // 默认:0/1
Fraction(int up0); // up0/1
Fraction(int up0, int down0); // up0/down0,自动约分 + 规范化符号
Fraction(const Fraction& other); // 拷贝构造
// 对象方法
int get_up() const; // 返回分子
int get_down() const; // 返回分母(恒为正)
Fraction negative() const; // 求负,返回新对象,自身不变
private:
int up; // 分子
int down; // 分母(恒为正)
// 内部工具函数
void normalize(); // 约分 + 规范化符号
static int gcd(int a, int b); // 最大公约数(返回正数)
};
// 方案2:命名空间自由函数(非友元,通过公有接口访问)
namespace frac {
void output(const Fraction& f);
Fraction add(const Fraction& a, const Fraction& b);
Fraction sub(const Fraction& a, const Fraction& b);
Fraction mul(const Fraction& a, const Fraction& b);
Fraction div(const Fraction& a, const Fraction& b);
}
#include "Fraction.h"
#include <iostream>
#include <stdexcept>
const std::string Fraction::doc =
"Fraction类 v 0.01版.\n"
"目前仅支持分数对象的构造、输出、加/减/乘/除运算.";
// ---- 构造函数 ----
Fraction::Fraction() : up(0), down(1) {}
Fraction::Fraction(int up0) : up(up0), down(1) {}
Fraction::Fraction(int up0, int down0) : up(up0), down(down0) {
if (down == 0)
throw std::invalid_argument("Fraction: 分母不能为0");
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); // down 已规范为正,直接取负分子即可
}
// ---- 内部工具 ----
int Fraction::gcd(int a, int b) {
if (a < 0) a = -a;
if (b < 0) b = -b;
while (b != 0) {
int r = a % b;
a = b;
b = r;
}
return a;
}
void Fraction::normalize() {
// 1. 分母恒为正,符号归到分子
if (down < 0) {
up = -up;
down = -down;
}
// 2. 约分
int g = gcd(up, down);
up /= g;
down /= g;
// 3. 分子为 0 时统一规范为 0/1
if (up == 0) down = 1;
}
// ---- 命名空间自由函数 ----
namespace frac {
void output(const Fraction& f) {
if (f.get_down() == 1)
std::cout << f.get_up(); // 整数:如 2
else
std::cout << f.get_up() << "/" << f.get_down();
}
Fraction add(const Fraction& a, const Fraction& b) {
int u = a.get_up() * b.get_down() + b.get_up() * a.get_down();
int d = a.get_down() * b.get_down();
return Fraction(u, d); // 构造时自动约分
}
Fraction sub(const Fraction& a, const Fraction& b) {
int u = a.get_up() * b.get_down() - b.get_up() * a.get_down();
int d = a.get_down() * b.get_down();
return Fraction(u, d);
}
Fraction mul(const Fraction& a, const Fraction& b) {
return Fraction(a.get_up() * b.get_up(),
a.get_down() * b.get_down());
}
Fraction div(const Fraction& a, const Fraction& b) {
if (b.get_up() == 0)
throw std::invalid_argument("Fraction: 除数为0");
return Fraction(a.get_up() * b.get_down(),
a.get_down() * b.get_up());
}
} // namespace frac
#include <iostream>
#include "Fraction.h"
using namespace frac; // 让 add/sub/... 直接可用
using std::cout;
using std::endl;
int main() {
cout << Fraction::doc << endl << endl;
// 构造测试
Fraction f1(2); // 2/1
Fraction f2(2, -3); // -2/3
Fraction f3(f2); // -2/3
Fraction f4 = f1; // 拷贝
cout << "f1 = "; output(f1); cout << endl; // 2
cout << "f2 = "; output(f2); cout << endl; // -2/3
cout << "f3 = "; output(f3); cout << endl; // -2/3
cout << "f4 = "; output(f4); cout << endl; // 2
// 化简测试
Fraction f5(-4, 10);
cout << "f5(-4/10) = "; output(f5); cout << endl; // -2/5
// 求负测试
Fraction f6 = f2.negative();
cout << "-f2 = "; output(f6); cout << endl; // 2/3
cout << "f2(原值不变) = "; output(f2); cout << endl; // -2/3
// 四则运算测试
Fraction a(1, 2), b(1, 3);
cout << "add(1/2,1/3) = "; output(add(a, b)); cout << endl; // 5/6
cout << "sub(1/2,1/3) = "; output(sub(a, b)); cout << endl; // 1/6
cout << "mul(1/2,1/3) = "; output(mul(a, b)); cout << endl; // 1/6
cout << "div(1/2,1/3) = "; output(div(a, b)); cout << endl; // 3/2
// 异常测试:分母为0
try {
Fraction bad(1, 0);
} catch (const std::exception& e) {
cout << "捕获异常: " << e.what() << endl;
}
// 异常测试:除数为0
try {
Fraction zero(0);
output(div(a, zero));
} catch (const std::exception& e) {
cout << "捕获异常: " << e.what() << endl;
}
return 0;
}
- 分数运算( output/add/sub/mul/div ),你选择的是哪种设计方案?你的决策理由?
我使用了方案2:分数类+命名空间自由函数
理由:。理由:类提供了公有get_up()/get_down(),自由函数通过这些公有接口即可完成计算,无需破坏封装。放进命名空间 frac 避免污染全局。
5.实验总结
- 1.const成员函数才能被const对象调用,static成员不属于任何对象,const成员函数可以合法修改它。
- 2.friend友元慎用,共有接口优先,友元会破坏类的封装性。
- 3.四个任务都采用「头文件声明 + 源文件实现 + 测试模块」的多文件组织,我体会到声明与定义分离、接口与实现解耦,是 C++ 工程的基本素养。
- 4.在构造和运算时主动校验非法输入、用异常明确传递错误,是健壮设计的一部分。




浙公网安备 33010602011771号