实验二
实验任务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 << ")";
}
task.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,说明它们分别触发了哪个构造函数。
- 普通构造函数
T(int x = 0, int y = 0);
功能:创建对象时初始化成员,并且有默认参数x=0,y=0。
调用时机:定义对象时,T a; T a(1,2);
特点:一个类可以有多个构造函数,通过不同的参数列表重载。
- 拷贝构造
T(const T &t);
功能:用已有对象复制生成新对象,且不会修改原对象。
调用时机:T b=a;用a来初始化b;函数值传递,参数是T类型;函数按值返回对象(编译器没做返回值优化时)
- 移动构造
T(T &&t);
功能:接管右值的资源,避免拷贝。新建对象、但不复制数据,直接接管t手里的资源(堆内存、动态数组等)
注意
1.&&右值引用,值能接收临时对象、std::move之后的对象
2.原来的对象t资源被抢走,编程空壳,不能再正常使用它
3.目的:省去大块内存拷贝,提升效率
调用时机:用临时对象初始化:T a=T(1,2);T a=move(b) ,把左值转为右值
- 析构函数
~T();
功能:释放对象占用资源
调用时机:局部对象出作用域;delete释放堆对象;程序结束销毁全局对象。
- t1-t4
T t1;//带默认参数的普通构造,初始化为t1(0,0)
T t2(3, 4);//有参数普通构造
T t3(t2);//拷贝构造
T t4(std::move(t2));//移动构造
问题2:
t.cpp中,line8-10,剪切到t.h的末尾,重新编译,程序能否正确编译。如不能,以截图形式给出报错信息,分析原因。
不能正常编译
- 报错信息

头文件和两个源程序独立编译时没有问题,链接时出现问题
截图中显示:multiple definition,重复定义
- 问题分析
t.cpp和task.cpp同时include<t.h>,所以当静态成员变量的定义写在t.h时,它会在t.cpp和task.cpp中分别定义一次,当链接时就会发生重复定义,链接器不知道用哪一份,然后报错。
问题3:
类T的测试模块
test 中,说明对象 t1-t4 的作用域和生命期。并思考:在这个作用域内,能否通过 t1 访
问其私有成员 m1、m2?这体现了类的什么特性?
t1-t4的作用域是包含他们的花括号内,生命期是从他们创建开始到花括号结束。
不能通过t1,访问私有成员m1、m2,只有类的成员函数和友员函数才能访问。体现了封装
问题4:
throw 功能:
throw 表达式
- 主动抛出一个异常对象,中断当前正常执行流,去匹配最近的catch
- 如果没有匹配的catch,程序会调用std::terminate终止
把t.cpp中T::MAX_CNT值改成2,重新编译、运行程序。观察输出,程序是正常结束还是崩溃了?给出截图运行结果
![image]()
程序崩溃了
如果崩溃了,已经创建的对象(如t1),会被正常销毁吗?给出答案,并说明理由。
会正常销毁
理由:
当throw抛出异常,c++会执行栈展开:沿着调用栈向上回溯,所有已经完全构造成功的对象,会自动调用析构函数释放资源;
任务2
此部分书写内容:
分别给出Complex.h, Complex.cpp, task2.cpp源码及运行测试截图
代码
Complex.h
#pragma once
#include<iostream>
#include<string>
class Complex{
public:
static const std::string doc;
Complex();
Complex(double x0,double y0);
Complex(double r);
~Complex();
Complex& operator=(Complex &&complex);
Complex& operator=(const Complex &complex);
Complex(const Complex &complex);
Complex(Complex &&complex);
double real()const;
double imag()const;
void add(const Complex& c);
private:
double real_,imag_;
friend void output(const Complex &c);
friend double abs(const Complex &c);
friend bool is_equal(const Complex &c1,const Complex &c2);
friend bool is_not_equal(const Complex &c1,const Complex &c2);
friend Complex add(const Complex &c1,const Complex &c2);
};
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 x0,double y0):real_{x0},imag_{y0}{
};
Complex& Complex::operator=(const Complex &complex){
if(this==&complex)
return *this;
real_=complex.real_;
imag_=complex.imag_;
return *this;
}
Complex::Complex(double r):real_{r},imag_{0}{};
Complex::Complex(const Complex &complex):real_{complex.real_},imag_{complex.imag_}{};
Complex::Complex(Complex &&complex):real_{complex.real_},imag_{complex.imag_}{};
Complex& Complex::operator=(Complex &&complex){
if(this == &complex)
return *this;
real_ = complex.real_;
imag_ = complex.imag_;
return *this;
}
double Complex::real()const{
return real_;
}
double Complex::imag()const{
return imag_;
}
void Complex::add(const Complex& c){
real_+=c.real_;
imag_+=c.imag_;
}
Complex::~Complex()=default;
void output(const Complex& c){
if(c.imag_>=0){
std::cout<<c.real_<<"+"<<c.imag_<<"i";}
else{
std::cout<<c.real_<<c.imag_<<"i";
}
}
double abs(const Complex& c){
double r=sqrt((double)c.real_*c.real_+c.imag_*c.imag_);
return r;
}
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.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:
在测试代码中,c6是cons对象。
① 为了让 c6.real() 和 c6.imag() 能编译通过,在设计 Complex 类的成员函数时,必须加上什么关键字?如果不加,编译器会报什么错?(请简述或截图报错信息)。
回答
const, 因为const对象只能调用const函数,编译器会报错:cannot call non-const member function on const object,不能在const对象上调用普通成员函数。
② 作为const对象,c6在初始化后允许再被修改。在测试代码中添加执行c6.add(c2);吗?为什么?这体现了类的什么保护机制?
回答
编译不通过。add()是const成员函数,会修改对象内部成员;const Complex c6是常量对象,不允许修改对象状态,体现const常量对象保护机制:const对象禁止调用会修改自身的普通成员函数,保证对象状态不被修改
问题2:
比较自定义类Complex 和标准库模板类运算是否存在内在关联呢?
回答
std::complex
普通命名函数和运算符重载内在关联:运算符底层本质也是函数调用;运算发重载就是把普通函数封装成运算符语法。
问题3:
① 本练习中,output 、abs 、add (非成员版本)等被设为Complex的友元。这是必须的吗?如果将其声明为普通非成员函数(不用friend ),能否实现相同的功能?简述思路。
回答
不是必须的
可以不写friend。思路:类对外提供real()、imag()的public get接口;普通非成员函数调用这两个public接口拿到实部虚部完成计算,不需要直接访问私有成语。
②标准库std::complex是否把abs设为友元
回答
不是友元,是普通非成员函数,通过public接口获取实部虚部,参考 cppreference:https://en.cppreference.com/w/cpp/numeric/complex/abs
③friend
回答
友元使用场景:需要频繁访问私有成员、运算符重载等;尽量少用,会破坏封装。优先使用 public 接口;仅在效率、语法必须场景才使用 friend。
任务3
代码
PlayControl.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;
};
PlayControl.cpp
#include "PlayerControl.h"
#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=control_str;//拷贝一个副本,后面只修改副本
for(auto &ch:s){
ch=static_cast<char>(tolower(static_cast<unsigned char>(ch)));
}
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自增 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();
}
运行截图

问题回答
接口void execute(ControlType cmd) const;是const成员函数,为什么在其内部实现允许代码
++total_cnt ?
回答
const修饰成员函数:禁止修改本对象的非静态实例成员(this->xxx);
toltal_cnt是static静态成员,不属于任何一个对象实例,不依赖this指针访问,不受成员函数const限制,因此可以修改
思考(选做*)
如果希望模拟播放控制时,输出控制更现代(使用
emoji),如以下测试截图所示。如何调整代码实现?
如选做,给出实现emoji输出的PlayerControl.h, PlayerControl.cpp, task3.cpp源码及运行测试结果截图
任务4
代码
Fraction.h
#pragma once
#include<string>
class Fraction{
public:
static const std::string doc;
Fraction(int up0=0,int down0=1);
Fraction(const Fraction &f);
Fraction negative()const;
int get_up()const ;
int get_down() 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;
static int gcd(int a,int b);
void reduce();
};
Fraction.cpp
#include"Fraction.h"
#include<iostream>
#include<stdexcept>
#include<algorithm>
const std::string Fraction::doc="Fraction类 v 0.01版.\n目前仅支持分数对象的构造、输出、加/减/乘/除运算.";
int Fraction::gcd(int a,int b){
a=std::abs(a);
b=std::abs(b);
while(b!=0){
int t=a%b;
a=b;
b=t;
}
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, int down0):up{up0}, down{down0}{
if(down0 == 0){
throw std::invalid_argument("Fraction: 分母不能为0");
}
reduce();
}
Fraction::Fraction(const Fraction &f):up{f.up}, down{f.down}{}
Fraction Fraction::negative() const{
return Fraction(-up, down);
}
int Fraction::get_up() const { return up; }
int Fraction::get_down() const { return down; }
void output(const Fraction& f){
if(f.down == 1){
std::cout << f.up;
}else{
std::cout << f.up << "/" << f.down;
}
}
Fraction add(const Fraction& a,const Fraction& b){
int new_up = a.up*b.down + b.up*a.down;
int new_down = a.down * b.down;
return Fraction(new_up, new_down);
}
Fraction sub(const Fraction& a,const Fraction& b){
int new_up = a.up*b.down - b.up*a.down;
int new_down = a.down * b.down;
return Fraction(new_up, new_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);
}
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();
}
运行截图

问题
分数运算(output/add/sub/mul/div ),你选择的是哪种设计方案?你的决策理由?
方案1:分数类 + 友元函数
方案2:分数类 + 命名空间自由函数
回答
选择方案 1:分数类 + 友元函数。
理由:加减乘除输出需要频繁访问约分后的私有分子、分母;使用友元直接访问私有成员,不需要反复调用 get 接口,代码简洁;本实验运算逻辑和分数内部存储强耦合,适合友元。
五、实验总结(选)
此部分书写内容:(可包括但不限)
提炼本次实验的核心收获与思考
记录新发现、真实感受与待解疑问
任意想补充的反馈或分享


浙公网安备 33010602011771号