实验二
实验任务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类对象数目
};
点击查看代码
#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 << ")";
}
点击查看代码
#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();
}
答:T(int x=0,int y=0) ,用 x,y 来初始化 m1,m2,创建对象、用参数构造对象时调用;T(const T &t),用同类型左值对象复制初始化,在已有对象需要复制构造新对象时调用;T(T &&t),用右值对象构造,在用 std::move( ) 或右值构造时调用;~T() ,打印析构信息,对象生命期结束、离开作用域时调用。
t1普通构造,t2普通/复制/移动构造,t3复制构造,t4移动构造。
问题2:把 t.cpp 第8–10行剪切到 t.h 末尾,能否正确编译?
答:不能正确编译。
运行报错截图:

原因分析:将静态成员数据的类外定义剪切到头文件 t.h 后,因为 task.cpp和 task1.cpp 都包含了该头文件,导致这两个翻译单元都包含了这些静态成员的定义。在链接阶段,链接器发现这三个变量(T::doc、T::MAX_CNT、T::current_cnt)存在多重定义(multiple definition),违反了C++的单一定义规则,因此报错。
问题3:t1–t4 的作用域和生命期;能否通过 t1 访问私有成员 m1、m2?
答:它们的作用域:从各自定义点开始,到该内层 } 结束。
生命期:自动存储期。进入定义点时构造,离开内层作用域时按构造逆序析构,即 t4 → t3 → t2 → t1。
在这个作用域内,不能通过 t1.m1、t1.m2 直接访问私有成员。因为 m1,m2 是 private,只有类 T 的成员函数和友元函数可以访问。output(t1) 能访问,是因为 output 是 T 的友元。
这体现类的封装/信息隐藏和访问权限控制特性。
问题4:throw 的作用;把 MAX_CNT 改成 2 后的行为
答:程序异常中止
运行结果截图:

将 T::MAX_CNT 的值改成 2 后,重新编译运行。观察输出,程序崩溃(异常终止)。当试图创建 t3 时,由于当前对象数量已经达到上限 2,抛出了 std::runtime_error 异常。由于主程序中没有任何 try-catch 块来捕获这个异常,系统调用了 terminate 终止了程序(如截图所示)。
如果崩溃了,已经创建的对象(如 t1、t2)不会被正常销毁。
理由:在 C++ 中,如果抛出的异常没有被捕获,是否进行栈展开(Stack Unwinding,即调用局部对象的析构函数)是实现(编译器)相关的。在常用的 GCC 编译器下,未捕获异常会导致直接调用 std::terminate(),此时不会执行栈展开,因此 t1 和 t2 的析构函数不会被调用。从运行截图中也能看出,直到程序终止,控制台都没有输出 T destructor called.。
实验任务2
1.Complex.h
点击查看代码
#pragma once
#include <string>
class Complex {
public:
static const std::string doc;
Complex(double real = 0.0, double imag = 0.0);
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 m_real;
double m_imag;
};
点击查看代码
#include "Complex.h"
#include <cmath>
#include <iostream>
const std::string Complex::doc{"a simplified complex class"};
Complex::Complex(double real, double imag)
: m_real{real}, m_imag{imag} {
}
double Complex::real() const {
return m_real;
}
double Complex::imag() const {
return m_imag;
}
void Complex::add(const Complex& other) {
m_real += other.m_real;
m_imag += other.m_imag;
}
void output(const Complex& c) {
std::cout << c.m_real;
if (c.m_imag < 0) {
std::cout << " - " << -c.m_imag;
} else {
std::cout << " + " << c.m_imag;
}
std::cout << "i";
}
double abs(const Complex& c) {
return std::sqrt(c.m_real * c.m_real + c.m_imag * c.m_imag);
}
Complex add(const Complex& a, const Complex& b) {
return Complex(a.m_real + b.m_real, a.m_imag + b.m_imag);
}
bool is_equal(const Complex& a, const Complex& b) {
return a.m_real == b.m_real && a.m_imag == b.m_imag;
}
bool is_not_equal(const Complex& a, const Complex& b) {
return !is_equal(a, b);
}
点击查看代码


3.问题1:
① 为了让 c6.real() 和 c6.imag() 能编译通过,在设计 Complex 类的成员函数时,必须加上什么关键字?如果不加,编译器会报什么错?
答:必须加上const 关键字;如果不加,编译器会报类似于 passing 'const Complex' as 'this' argument discards qualifiers 的错误。这是因为 c6 是常对象,常对象只能调用常成员函数。
② 在测试代码中添加执行 c6.add(c2);,能编译通过吗?为什么?这体现了类的什么保护机制?
答:不能编译通过。
原因:c6 是 const 对象,而 add() 方法会修改对象本身的数据成员,因此不能声明为 const 成员函数。const 对象不允许调用非 const 的成员函数,编译器会直接拦截。
体现机制:这体现了类的 常对象保护机制(或数据保护机制、const 保护),保证了常对象在初始化后数据绝对安全,不会被意外修改。
问题2:
比较自定义类 Complex 和标准库模板类 complex 的用法,在使用形式上,哪种更简洁?据此推断函数和运算是否存在内在关联呢?
答:简洁性:标准库 std::complex
内在关联:存在内在关联。C++ 中的运算符本质上是函数,标准库通过运算符重载机制,将 +、+=、==、<< 等符号重载为了对应的函数。例如 c2 + c3 实际上底层调用的就是类似 operator+(c2, c3) 的函数。自定义类也可以用重载实现同样的效果,只是实验任务要求我们用普通成员函数/友元函数的形式实现。
问题3:
① 本练习中,output、abs、add(非成员版本)等被设为 Complex 的友元。这是必须的吗?如果将其声明为普通非成员函数(不用 friend),能否实现相同的功能?简述思路。
答:不是必须的。
思路:如果不使用 friend,只要类提供了公有的 real() 和 imag() 接口,普通非成员函数同样可以实现:
output(c) 可以用 cout << c.real() << ... << c.imag() 实现。
abs(c) 可以用 sqrt(c.real()c.real() + c.imag()c.imag()) 实现。
add(a, b) 可以用 Complex(a.real()+b.real(), a.imag()+b.imag()) 返回新对象实现。
设为友元的好处是可以直接访问私有成员,省去了频繁调用函数的开销,代码写起来也更直接。
② 标准库 std::complex 是否把 abs 设为友元?
答:不是。std::abs 是定义在 std 命名空间下的非成员模板函数,标准库并没有将其声明为 std::complex 的友元(因为标准库 complex 的实部和虚部可以通过 real() 和 imag() 直接获取)。
页面链接:https://en.cppreference.com/w/cpp/numeric/complex/abs
不是。std::abs 是定义在 std 命名空间下的非成员模板函数,标准库并没有将其声明为 std::complex 的友元(因为标准库 complex 的实部和虚部可以通过 real() 和 imag() 直接获取)。
③ 工业场景中,什么时候才考虑使用 friend?和AI讨论后,简洁概括你的思考和结论。(限150字内)
答:在实际开发中,优先通过公有接口暴露数据。只有当事先设计的非成员函数(特别是流输出运算符 operator<<、对称的二元运算符 operator+ 等)必须直接访问类的内部私有数据,且仅靠公有 getter/setter 会严重降低效率或导致代码极为繁琐时,才应考虑使用 friend。友元会破坏封装,应慎用,仅在极其紧密的协作类/函数中使用。
实验任务3
1.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; // 记录播放控制操作总次数
};
点击查看代码
#include "PlayerControl.h"
#include <algorithm>
#include <iostream>
#include <cctype>
// 静态成员初始化
int PlayerControl::total_cnt = 0;
PlayerControl::PlayerControl() {
}
// 将输入字符串统一转为小写,实现大小写不敏感匹配
ControlType PlayerControl::parse(const std::string& control_str) {
std::string s = control_str;
std::transform(s.begin(), s.end(), s.begin(),
[](unsigned char c) { return std::tolower(c); });
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; // const成员函数可以修改static成员
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 << "[Unknown] Unknown control command\n";
break;
}
}
// 获取当前总控制次数
int PlayerControl::get_cnt() {
return total_cnt;
}
点击查看代码
#include <iostream>
#include <string>
#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?
答:因为 total_cnt 是类的 静态数据成员(static)。const 成员函数限制的是不能修改当前对象的非静态数据成员(即限制 this 指针指向的内容)。而 static 成员属于整个类,不属于某个具体的对象,没有 this 指针的参与,因此 const 成员函数允许修改类的静态成员数据。
实验任务4
1.Fraction.h
点击查看代码
#pragma once
#include <string>
class Fraction {
public:
// 类属性:类说明,公有,常量
static const std::string doc;
// 构造函数(带默认参数)
Fraction(int up0 = 0, int down0 = 1);
// 对象方法
int get_up() const { return up; }
int get_down() const { return down; }
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; // 分母
// 内部工具函数:用于化简和符号处理
void normalize();
};
点击查看代码
#include "Fraction.h"
#include <iostream>
#include <stdexcept>
#include <cstdlib> // std::abs
// 静态常量成员类外初始化
const std::string Fraction::doc =
"Fraction类 v 0.01版.\n"
"目前仅支持分数对象的构造、输出、加/减/乘/除运算.";
// 内部辅助函数:求最大公约数
static int gcd(int a, int b) {
a = std::abs(a);
b = std::abs(b);
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a == 0 ? 1 : a;
}
// 构造函数
Fraction::Fraction(int up0, int down0) : up{up0}, down{down0} {
if (down == 0) {
throw std::invalid_argument("Fraction: 分母不能为0");
}
normalize();
}
// 内部工具函数:统一负号与化简
void Fraction::normalize() {
// 1. 统一负号:如果分母为负,将负号移到分子上
if (down < 0) {
up = -up;
down = -down;
}
// 2. 约分:分子分母同除以最大公约数
int g = gcd(up, down);
up /= g;
down /= g;
}
// 求负:自身不变,返回求负后的新对象
Fraction Fraction::negative() const {
return Fraction(-up, down);
}
// 友元函数:输出
void output(const Fraction& f) {
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) {
if (b.up == 0) {
throw std::invalid_argument("Fraction: 除数不能为0");
}
return Fraction(a.up * b.down, a.down * b.up);
}
点击查看代码
#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();
}

3.问题:分数运算(output/add/sub/mul/div)你选择的是哪种设计方案?你的决策理由?
答:我选择的是 方案1:分数类 + 友元函数。
决策理由:
调用简洁:根据题目给定的 task4.cpp 测试代码,调用方式是 add(f1, f2)、output(f1) 等,无需任何前缀。使用友元函数可以完美契合这种调用形式,代码看起来最干净。
实现方便:在 add、sub、mul、div 等运算中,需要直接访问分数的分子 up 和分母 down 来构造新的分数对象。设为友元函数可以直接访问私有成员,省去了频繁调用 get_up() 和 get_down() 的麻烦,执行效率也略高。
浙公网安备 33010602011771号