实验2
1. 实验任务1
分别给出t.h, t.cpp, task1.cpp源码
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,说明它们分别触发了哪个构造函数。
1) T(int x=0,int y=0)普通构造函数:
功能:创建新对象,初始化对象数据成员 m1,m2;对象计数 + 1;
调用时机:定义对象T t1; T t2(3,4);
2) T(const T &t)拷贝构造函数:
功能:用已有同类型对象,复制一份生成新对象;计数 + 1;
调用时机:T t3(t2),对象拷贝初始化;
3) T(T&& t)移动构造函数:
功能:接管临时 / 右值对象资源生成新对象;计数 + 1;
调用时机:T t4(std::move(t2))传入右值
4)~T()析构函数:
功能:对象销毁前清理,对象计数current_cnt--;
调用时机:对象离开作用域生命周期结束。
t1:普通构造函数
t2:普通构造函数
t3:拷贝构造函数
t4:移动构造函数
问题2: t.cpp中,line8-10,剪切到t.h的末尾,重新编译,程序能否正确编译。 如不能,以截图形式给出报错信息,分析原因。
将三行 static 初始化代码剪切放到 t.h 末尾,编译报错。
T::doc、T::MAX_CNT、T::current_cnt属于类静态成员的定义初始化。头文件会被多个.cpp源文件多次 include;放在头文件会导致多重定义 multiple definition 链接错误。
类内只是静态成员声明;静态数据成员定义初始化必须放在.cpp实现文件,保证整个项目只被编译一次。
问题3: 类T的测试模块 test 中,说明对象 t1-t4 的作用域和生命期。并思考:在这个作用域内,能否通过 t1 访 问其私有成员 m1、m2?这体现了类的什么特性?
t1,t2,t3,t4 定义在内层{ }块中;作用域为内层花括号内部;生命周期从定义语句开始,遇到}右花括号,对象全部析构销毁。
在 test 函数中,不能直接t1.m1访问 m1,m2;m1、m2 标记private私有。
体现封装特性:访问控制,数据隐藏。外部不能直接访问私有成员,只能通过类提供的成员函数、友元访问。
问题4: t.cpp中包含了头文件 #include ,构造函数中均使用了以下代码。使用搜索引擎/AI查询 throw 功能。 把t.cpp中T::MAX_CNT值改成2,重新编译、运行程序。观察输出,程序是正常结束还是崩溃了?给出截 图运行结果。 如果崩溃了,已经创建的对象(如t1),会被正常销毁吗?给出答案,并说明理由
throw:抛出异常对象,中断正常执行流程,交给上层try‑catch处理;没有捕获异常程序终止。
修改MAX_CNT=2。
执行时:t1、t2 创建成功;尝试创建 t3,此时 current_cnt 达到 2,throw 抛出异常;main 没有写 try‑catch 捕获异常。
已经构造完成的局部对象 t1,t2:会正常析构销毁。C++ 栈展开(stack unwinding)机制,抛出异常离开局部作用域时,已经完全构造完成的栈对象会自动调用析构。未构造完成的对象不会调用析构。
2. 实验任务2
分别给出Complex.h, Complex.cpp, task2.cpp源码
Complex.h:
#pragma once
#include <string>
class Complex {
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);
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_;
};
Complex.cpp:
#include "Complex.h"
#include <iostream>
#include <cmath>
const std::string Complex::doc = "a simplified complex class";
Complex::Complex() : real_(0), imag_(0) {}
Complex::Complex(double r) : real_(r), imag_(0) {}
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 &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);
}
task2:
#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是cons对象。 ① 为了让 c6.real() 和 c6.imag() 能编译通过,在设计 Complex 类的成员函数时,必须加上什么关 键字?如果不加,编译器会报什么错?(请简述或截图报错信息)
必须给成员函数real()、imag()末尾加 const,变成double real() const;。
不加 const 报错:不能调用 const 对象的非 const 成员函数;const 对象只能调用 const 成员函数。
② 作为const对象,c6在初始化后允许再被修改。在测试代码中添加执行 吗?为什么?这体现了类的什么保护机制?
问题2: 比较自定义类 Complex 和标准库模板类 运算是否存在内在关联呢
原因:add()是非 const 成员函数,内部修改对象数据;c6是 const 对象,禁止修改。
体现const 常量对象保护机制,防止修改常量对象状态。
问题3: ① 本练习中, output 、 abs 、 add (非成员版本)等被设为Complex的友元。这是必须的吗?如果将 其声明为普通非成员函数(不用 friend ),能否实现相同的功能?简述思路。
friend 不是必须。普通非成员函数也可以实现;
思路:给类提供 public getter 接口real()、imag(),外部普通函数调用 public 接口读取实部虚部,不需要直接访问私有成员,就不用友元。
3. 实验任务3
分别给出PlayerControl.h, PlayerControl.cpp, task3.cpp源码
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);
void execute(ControlType cmd) const;
static int get_cnt();
private:
static int total_cnt;
};
PlayerControl.cpp:
#include "PlayerControl.h"
#include <algorithm>
#include <iostream>
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;
else if(s == "pause") return ControlType::Pause;
else if(s == "next") return ControlType::Next;
else if(s == "prev") return ControlType::Prev;
else if(s == "stop") return ControlType::Stop;
else 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;
}
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();
}
及运行测试截图

问题回答
接口 void execute(ControlType cmd) const;是const成员函数,为什么在其内部实现允许代码 ++total_cnt ?
const修饰成员函数:禁止修改本对象的普通非静态成员变量;
total_cnt是static静态类成员,不属于某一个对象实例,属于整个类。const 成员函数不会限制静态成员的读写。
4. 实验任务4
分别给出程序Fraction.h, Fraction.cpp, task4.cpp源码
Fraction.h:
#pragma once
#include <string>
namespace frac {
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;
private:
int up;
int down;
void reduce(); //内部工具:分数约分,保证分母>0
};
//命名空间自由函数
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 <iostream>
#include <stdexcept>
#include <algorithm>
namespace frac {
const std::string Fraction::doc = R"(Fraction类 v 0.01版.
目前仅支持分数对象的构造、输出、加/减/乘/除运算.)";
//求最大公约数
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;
}
//约分,保证分母为正数
void Fraction::reduce() {
int g = gcd(up, down);
up /= g;
down /= g;
if(down < 0) {
up = -up;
down = -down;
}
}
Fraction::Fraction(int up0): up(up0), down(1) { reduce(); }
Fraction::Fraction(int up0, int down0): up{up0}, down{down0} {
if(down0 == 0) {
throw std::invalid_argument("Fraction: 分母不能为0");
}
reduce();
}
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) {
int u = f.get_up();
int d = f.get_down();
if(d == 1) {
std::cout << u;
} else {
std::cout << u << "/" << d;
}
}
Fraction add(const Fraction& f1, const Fraction& f2) {
int u1 = f1.get_up(), d1 = f1.get_down();
int u2 = f2.get_up(), d2 = f2.get_down();
int new_up = u1*d2 + u2*d1;
int new_down = d1*d2;
return Fraction(new_up, new_down);
}
Fraction sub(const Fraction& f1, const Fraction& f2) {
int u1 = f1.get_up(), d1 = f1.get_down();
int u2 = f2.get_up(), d2 = f2.get_down();
int new_up = u1*d2 - u2*d1;
int new_down = d1*d2;
return Fraction(new_up, new_down);
}
Fraction mul(const Fraction& f1, const Fraction& f2) {
int u1 = f1.get_up(), d1 = f1.get_down();
int u2 = f2.get_up(), d2 = f2.get_down();
return Fraction(u1*u2, d1*d2);
}
Fraction div(const Fraction& f1, const Fraction& f2) {
int u1 = f1.get_up(), d1 = f1.get_down();
int u2 = f2.get_up(), d2 = f2.get_down();
return Fraction(u1*d2, d1*u2);
}
}//namespace frac
task4.cpp:
#include <iostream>
#include "Fraction.h"
void test1() {
using std::cout;
using std::endl;
using namespace frac;
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;
using namespace frac;
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();
}
及运行测试截图

问题回答 分数运算( output/add/sub/mul/div ),你选择的是哪种设计方案?你的决策理由?
选择方案2:分数类 + 命名空间自由函数
理由:运算属于类外部操作,不需要直接访问私有;提供 public get 接口即可,不破坏封装;友元会破坏封装性。

浙公网安备 33010602011771号