实验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();
}
2.运行测试截图

3.问题:
-
1:T(int x = 0, int y = 0) 普通构造函数:
功能:在对象被创建时利用特定的值构造对象,将对象初始化为一个特定的状态
调用时机:对象创建时被调用T(const T &t) 复制构造函数:
功能:使用一个已经存在的对象去初始化同类的一个新对象
调用时机:用类的一个对象去初始化该类的另一个对象;如果函数的形参是类的对象,调用函数时,进行形参和实参结合时;如果函数的返回值是类的对象,函数执行完成返回调用者时T(T &&t) 移动构造函数:
功能:“窃取”一个右值(临时对象或即将销毁的对象)的资源来初始化新对象,避免不必要的拷贝
调用时机:在用右值初始化新对象时(如使用 std::move(),或绑定到函数返回的临时对象)~T() 析构函数:
功能:完成对象被删除前的一些清理工作
调用时机:对象的生存期即将结束的时刻被自动调用普通构造函数 t1,t2
复制构造函数 t3
移动构造函数 t4(std::move(t2) 将t2转换为右值) -
2:不能。把静态成员变量的定义放到了 t.h 头文件的末尾,t.cpp 和 task1.cpp 都#include "t.h",因此在编译阶段t.cpp 和 task1.cpp 各自的目标文件.o里都包含了这三个变量的定义,即头文件被多个源文件包含导致重复

-
3:作用域:t1-4都是test()函数内部
生命期:从被定义开始到程序执行完test函数时结束,然后按照与构造相反的顺序被自动销毁并调用析构函数
不能,m1和m2在t.h中被声明在private:访问控制符之下,类的私有成员只能在类内部被访问,外部的test函数无法直接访问。体现了类的封装性和保护性能。 -
4:throw是C++中用于抛出异常的关键字。当程序遇到无法处理的错误时,可以使用throw抛出一个异常对象,程序的控制流会立即中断当前函数的执行,并沿着调用栈向上寻找匹配的catch块来处理该异常。
崩溃了。不会被正常销毁。
程序输出了:
T constructor called.
T constructor called.
terminate called after throwing...
没有出现T destructor called.
说明程序崩溃后没有离开作用域,析构函数没有被调用
![实验1-4]()
任务2
1.源代码
- Complex.h
点击查看代码
#pragma once
#include <string>
class Complex
{
//友元函数
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);
public:
//类属性
static std::string doc;
//构造函数
Complex(double r = 0.0, double i = 0.0);
Complex(const Complex& other);
//接口
double real() const;
double imag() const;
void add(const Complex& other);
private:
//对象属性
double real_;
double imag_;
};
- Complex.cpp
点击查看代码
#include "Complex.h"
#include <iostream>
#include <cmath>
std::string Complex::doc = "a simplified Complex class";
//构造函数
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_ << " + " << 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.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;
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();
}
2.运行测试截图


3.问题
- 1:
必须加const关键字

不能.
c6是const对象,而add函数是非const成员函数,const对象不能调用非const成员函数。
const关键字在编译期间保证对象只读,防止意外修改
-
2:标准库类模板更简洁。
存在内在关联。运算就是调用对应运算符的函数 -
3:不一定。可以把real_和imag_放入public:区,普通函数也可以调用,但是缺乏隐私性。
任务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;
};
- 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 lower = control_str;
std::transform(lower.begin(), lower.end(), lower.begin(),[](char c)
{ return std::tolower(c); });
if (lower == "play") return ControlType::Play;
if (lower == "pause") return ControlType::Pause;
if (lower == "next") return ControlType::Next;
if (lower == "prev") return ControlType::Prev;
if (lower == "stop") return ControlType::Stop;
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();
}
2.运行测试截图

3.问题:因为total_cnt在类内被声明为静态成员变量,const不能修改的是对象的内部状态,而static属于类,它存储在静态存储区
任务4
1.源代码
- Fraction.h
点击查看代码
#pragma once
#include <string>
#include <iostream>
class Fraction {
public:
//类属性
static std::string doc;
//构造函数
Fraction(int up_ = 0, int down_ = 1);
Fraction(const Fraction& other) = default;
//接口
int get_up() const;
int get_down() const;
Fraction negative() const;
//友元函数
friend void output(const Fraction& f);
friend Fraction add(const Fraction& f1, const Fraction& f2);
friend Fraction sub(const Fraction& f1, const Fraction& f2);
friend Fraction mul(const Fraction& f1, const Fraction& f2);
friend Fraction div(const Fraction& f1, const Fraction& f2);
private:
int up;
int down;
void simp();
};
- Fraction.cpp
点击查看代码
#include "Fraction.h"
#include <cmath>
#include <stdexcept>
std::string Fraction::doc =
"Fraction类 v 0.01版.\n"
"目前仅支持分数对象的构造、输出、加/减/乘/除运算.";
Fraction::Fraction(int up0, int down0) : up{up0}, down{down0} {
if (down == 0)
throw std::invalid_argument("Fraction: 分母不能为0");
simp();
}
int Fraction::get_up() const {
return up;
}
int Fraction::get_down() const {
return down;
}
Fraction Fraction::negative() const {
return Fraction(-up, down);
}
void Fraction::simp() {
if (up == 0) {
down = 1;
return;
}
if (down < 0) {
up = -up;
down = -down;
}
int min = down; //找最大公约数化简分数
for (int i = min; i >= 1; --i) {
if (up % i == 0 && down % i == 0) {
up /= i;
down /= i;
break;
}
}
}
void output(const Fraction& f) {
if (f.down == 1) {
std::cout << f.up;
} else {
std::cout << f.up << "/" << f.down;
}
}
Fraction add(const Fraction& f1, const Fraction& f2) {
int up1 = f1.up * f2.down + f2.up * f1.down;
int down1 = f1.down * f2.down;
return Fraction(up1, down1);
}
Fraction sub(const Fraction& f1, const Fraction& f2) {
int up2 = f1.up * f2.down - f2.up * f1.down;
int down2 = f1.down * f2.down;
return Fraction(up2, down2);
}
Fraction mul(const Fraction& f1, const Fraction& f2) {
int up3 = f1.up * f2.up;
int down3 = f1.down * f2.down;
return Fraction(up3, down3);
}
Fraction div(const Fraction& f1, const Fraction& f2) {
if (f2.up == 0) {
throw std::invalid_argument("Fraction: 分母不能为0");
}
int up4 = f1.up * f2.down;
int down4 = f1.down * f2.up;//乘倒数
return Fraction(up4, down4);
}
- 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();
}
2.运行测试截图

3.问题:方案1:分数类 + 友元函数
分数的分子和分母是私有属性,使用友元函数可直接访问这些私有成员,从而高效地进行加减乘除运算和化简,我也更加熟悉这种写法

浙公网安备 33010602011771号