实验2
实验内容
实验任务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
-
line7是带默认值带普通构造函数
- 功能:新建对象,用参数值初始化成员,带默认值可以无参构造
- 调用时机:传参或无参创建对象,显示构造临时对象
-
line8是复制构造函数
- 功能:用一个已存在的同类型对象,复制一份一模一样的对象副本
- 调用时机:用已有对象初始化新对象、函数参数值传对象、函数返回对象
-
line9是移动构造函数
- 功能:接管右值对象的资源,避免拷贝开销
- 调用时机:用std::move把左值转为右值来初始化新对象,接收临时对象
-
line10是析构函数
- 功能:对象销毁时做清理、计数减一
- 调用时机:对象离开作用域
-
t1t2触发普通构造,t3触发复制构造,t4触发移动构造
-
- 问题2

不能,因为这是静态成员类外初始化,如果放在头文件,多个源文件会对其重复定义。
- 问题3
- t1-4的作用域仅在test函数内部,生命周期是当test函数被调用时构造对象,当函数结束运行时,自动调用析构函数销毁对象。
- t1不能访问私有成员m1,m2,私有成员只能在类内部或类的友元函数访问,体现类的封装性。
- 问题4
- throw 是 C++ 异常抛出关键字:当满足条件时,主动抛出一个异常对象std::runtime_error;程序会立刻停止当前代码往下执行,向上寻找匹配的catch捕获块。
- 程序会崩溃,t3创建时会触发throw抛异常
![image]()
t1-2会被正常销毁,因为抛异常前t1-2就已经构造好了,会自动按照逆序调用析构函数销毁。
实验任务2
实验源码
- Complex.h源码
点击查看代码
#pragma once
#include<string>
class Complex{
public:
//静态说明类属性
static const std::string doc;
//构造
Complex(double r=0, double i=0);
Complex(const Complex& other);
//接口
double real() const;
double imag() const;
void add(const Complex& c);
//友元函数
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& a, const Complex& b);
friend bool is_not_equal(const Complex& a, const Complex& b);
private:
double m_real;
double m_imag;
};
- Complex.cpp源码
点击查看代码
#include "Complex.h"
#include <iostream>
#include <cmath>
// 静态常量类外初始化
const std::string Complex::doc{"a simplified complex class"};
// 普通构造
Complex::Complex(double r, double i) : m_real{r}, m_imag{i}
{
}
// 拷贝构造
Complex::Complex(const Complex& other)
: m_real{other.m_real}, m_imag{other.m_imag}
{
}
//接口
double Complex::real() const
{
return m_real;
}
double Complex::imag() const
{
return m_imag;
}
void Complex::add(const Complex& c)
{
m_real += c.m_real;
m_imag += c.m_imag;
}
// 友元
void output(const Complex& c)
{
std::cout << c.m_real;
if (c.m_imag >= 0)
{
std::cout << " + " << c.m_imag << "i";
}
else
{
std::cout << " - " << -c.m_imag << "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& c1, const Complex& c2)
{
return Complex(c1.m_real + c2.m_real, c1.m_imag + c2.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);
}
- 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
- 1.必须加const
2.会报错passing 'const Complex' as 'this' argument discards qualifiers,不能把const对象传给非const成员函数 - 不能编译通过
1.const对象不能调用非const成员函数
2.体现了类的常量保护机制
- 1.必须加const
- 问题2
1.std::complex使用形式更简洁。
2.存在内在关联,自定义的 add、is_equal、is_not_equal 本质就是运算符重载+=、+、==、!=;标准库就是通过运算符重载实现这种简洁写法 - 问题3
- 非必须,用real()、imag()接口访问私有成员
- std::complex 的 abs不是友元,它是独立非成员函数模板,依靠real()、imag()接口获取值
https://en.cppreference.com/cpp/numeric/complex/abs - friend 会破坏类的封装性,所以工业开发中应当谨慎使用。只有当外部函数 / 其他类需要频繁访问本类私有成员,新增公有 get 接口又会让接口臃肿、或者影响性能、不符合类的设计语义时,才考虑友元。
实验任务3
实验源码
- 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;
};
- PlayerControl.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;
// 全部转小写
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自增 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();
}
测试截图

回答问题
- const成员函数的限制时不允许修改这个对象自己的非静态成员变量。而total_cnt是static静态成员,它不属于任何一个对象,是属于整个类的,不在当前对象的内存空间里,不受成员函数后面const的约束。
实验任务4
实验源码
- Fraction.h源码
点击查看代码
#pragma once
#include<string>
class Fraction{
public:
//类属性
static const std::string doc;
//构造函数
Fraction(int up0,int down0=1);
Fraction(const Fraction& other);
//接口
int get_up() const;
int get_down() const;
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;
};
- Fraction.cpp源码
点击查看代码
#include "Fraction.h"
#include <iostream>
#include <stdexcept>
#include <algorithm>
const std::string Fraction::doc{"Fraction类 v 0.01版.\n目前仅支持分数对象的构造、输出、加/减/乘/除运算."};
//普通构造,分母不能为0,抛异常
Fraction::Fraction(int up0, int down0): up{up0}, down{down0}
{
if(down0 == 0)
{
throw std::invalid_argument("Fraction: 分母不能为0");
}
//约分
int a = std::abs(up);
int b = std::abs(down);
while(b != 0)
{
int temp = b;
b = a % b;
a = temp;
}
up/=a;
down/=a;
if(down0 < 0)
{
up = -up;
down = -down;
}
}
//拷贝构造
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(-this->up, this->down);
}
//友元
//输出
void output(const Fraction& f)
{ if(f.up==0)
std::cout<<0;
else 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)
{
int new_up = a.up * b.up;
int new_down = a.down * b.down;
return Fraction(new_up, new_down);
}
//除法
Fraction div(const Fraction& a, const Fraction& b)
{
int new_up = a.up * b.down;
int new_down = a.down * b.up;
return Fraction(new_up, new_down);
}
- 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();
}
测试截图

回答问题
1.我选择方案 1:分数类 + 友元函数。
2.决策理由:
友元函数可以直接访问私有成员up、down,不用通过接口访问,代码简洁直观,而且函数调用时也简洁。本实验规模小,友元带来的封装破坏影响有限,代码书写简单。
实验总结
本次实验我巩固了 C++ 面向对象编程知识。我掌握了构造函数、拷贝构造、静态成员、const 成员函数的用法,理解 const 成员不能修改对象非静态成员,但静态成员不受该限制。了解友元函数与命名空间自由函数两种外部函数设计方案的区别。同时学异常抛出处理,体会多文件分离的工程写法,认识到封装保护数据、合理选择设计方案对代码可读性和可维护性的意义。


浙公网安备 33010602011771号