实验二
实验任务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();
friend void output(const T &t);
static const std::string doc;
static const int MAX_CNT;
private:
int m1, m2;
static int current_cnt;
};
t.cpp
点击查看代码
#include "t.h"
#include <iostream>
#include <stdexcept>
#include <string>
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();
}
测试截图

-
普通构造函数 T(int x = 0, int y = 0):创建对象时给数据成员赋初值,没传参就用默认值 0。
-
复制构造函数 T(const T &t):用一个已经存在的对象,复制出一个内容相同的新对象。
-
移动构造函数 T(T &&t):用一个即将销毁的右值对象,把它的数据转交给新对象。
-
析构函数 ~T():对象生命期结束时由系统自动调用,做收尾工作;这里把对象计数减 1。
-
t1 没传参数,调用普通构造函数(用默认参数);
-
t2(3, 4) 调用普通构造函数;
-
t3(t2) 用已有对象 t2 复制,调用复制构造函数;
-
t4(std::move(t2)) 传的是右值,调用移动构造函数。
问题2:

这三行是静态成员的定义。头文件 t.h 会被 t.cpp 和 task1.cpp 两个源文件都包含,定义放进头文件后,每个编译单元都会各自生成一份 T::doc、T::MAX_CNT、T::current_cnt,链接时就出现重复定义
问题3:t1~t4 都定义在 test() 函数里那个内层花括号 { } 中;不能;体现了类的封装特性。
问题4:throw 的作用:主动抛出一个异常,打断当前正常执行流程,把错误信息交给上层去处理;这里构造函数发现对象数量达到上限时,就 throw 一个 runtime_error。
实验任务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 &c); // 复制构造函数
double real() const; // 返回复数实部
double imag() const; // 返回复数虚部
void add(const Complex &other); // 自身加上另一个复数:c1 += c2
friend void output(const Complex &c); // 以 a+bi 形式输出
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 re; // 实部
double im; // 虚部
};
Complex.cpp
点击查看代码
#include "Complex.h"
#include <iostream>
#include <cmath>
#include <string>
const std::string Complex::doc = "a simplified complex class";
// 普通构造函数
Complex::Complex(double r, double i): re{r}, im{i} {}
// 复制构造函数
Complex::Complex(const Complex &c): re{c.re}, im{c.im} {}
double Complex::real() const { return re; }
double Complex::imag() const { return im; }
// 自身 += other
void Complex::add(const Complex &other) {
re += other.re;
im += other.im;
}
// 友元:输出 a+bi 形式
void output(const Complex &c) {
std::cout << c.re;
if (c.im >= 0) {
std::cout << "+" << c.im << "i";
} else {
std::cout << "-" << -c.im << "i";
}
}
// 友元:求模
double abs(const Complex &c) {
return std::sqrt(c.re * c.re + c.im * c.im);
}
// 友元:两复数相加,返回新复数
Complex add(const Complex &a, const Complex &b) {
return Complex(a.re + b.re, a.im + b.im);
}
// 友元:判断相等
bool is_equal(const Complex &a, const Complex &b) {
return a.re == b.re && a.im == b.im;
}
// 友元:判断不相等
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:为了让 c6.real()、c6.imag() 能在 const 对象上调用,这两个成员函数必须加上 const 后缀,也就是常成员函数。如果不加,const 对象不能调用非 const 成员函数,编译器报错
编译通不过。因为 add() 会修改对象本身,是个非 const 成员函数;而 const 对象初始化之后不允许再被修改,所以编译器同样报 discards qualifiers 的错。这体现了类的 const 保护机制
问题2:标准库 std::complex 的写法更简洁;存在内在关联。
问题3:1.友元不是必须的。可以把 real()、imag() 做成公有的 const 访问器
2.标准库 std::complex 并没有把 abs 设为友元。
https://en.cppreference.com/cpp/numeric/complex/abs
3.friend 会破坏封装,只在两个类或函数关系特别紧密、又确实需要直接访问内部实现时才用,比如部分运算符重载、配合很频繁的辅助类
实验任务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 str = control_str;
// 统一转为小写
std::transform(str.begin(), str.end(), str.begin(), ::tolower);
// 匹配并返回对应的枚举值
if (str == "play") return ControlType::Play;
if (str == "pause") return ControlType::Pause;
if (str == "next") return ControlType::Next;
if (str == "prev") return ControlType::Prev;
if (str == "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();
return 0;
}
测试截图:

问题:因为 total_cnt 是 static 静态成员,它属于整个类,不属于某一个具体对象。const 修饰的是“不能修改当前这个对象的非静态数据成员”,而静态成员不绑定到具体对象,不受 this 指针 const 的限制,所以在 const 成员函数里照样可以修改它。
实验任务4
Fraction.h
点击查看代码
#pragma once
#include <string>
class Fraction {
public:
static const std::string doc; // 类说明信息,常量,公有
Fraction(int up0 = 0, int down0 = 1); // 构造:分母默认为 1
Fraction(const Fraction &f); // 复制构造
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, down; // 分子、分母,私有
void normalize(); // 内部工具:约分 + 把负号统一到分子
};
Fraction.cpp
点击查看代码
#include "Fraction.h"
#include <iostream>
#include <stdexcept>
#include <string>
#include <cstdlib>
const std::string Fraction::doc =
"Fraction类 v 0.01版. 目前仅支持分数对象的构造、输出、加/减/乘/除运算.";
// 求两个整数的最大公约数
static int gcd(int a, int b) {
a = std::abs(a);
b = std::abs(b);
while (b != 0) {
int r = a % b;
a = b;
b = r;
}
return a == 0 ? 1 : a;
}
// 约分 + 符号归一:分母为正,负号放在分子上
void Fraction::normalize() {
if (down < 0) {
up = -up;
down = -down;
}
int g = gcd(up, down);
up /= g;
down /= g;
if (up == 0) down = 1;
}
Fraction::Fraction(int up0, int down0): up{up0}, down{down0} {
if (down == 0)
throw std::invalid_argument("Fraction: 分母不能为0");
normalize();
}
Fraction::Fraction(const Fraction &f): up{f.up}, down{f.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) {
if (f.down == 1) {
std::cout << f.up;
} else {
std::cout << f.up << "/" << f.down;
}
}
// 加法:a + b
Fraction add(const Fraction &a, const Fraction &b) {
return Fraction(a.up * b.down + b.up * a.down, a.down * b.down);
}
// 减法:a - b
Fraction sub(const Fraction &a, const Fraction &b) {
return Fraction(a.up * b.down - b.up * a.down, a.down * b.down);
}
// 乘法:a * b
Fraction mul(const Fraction &a, const Fraction &b) {
return Fraction(a.up * b.up, a.down * b.down);
}
// 除法:a / b
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();
}
测试截图:

选择方案1:分数类 + 友元函数。
理由:output、add、sub、mul、div 都需要直接访问私有分子 up 和分母 down,做成友元最直接,且代码简洁。
实验总结
通过这次实验了解了类和对象、封装、访问权限控制、static、friend、const,构造和析构什么时候被调用、顺序是怎样的;const 对象只能调常成员函数;静态成员属于类而不属于对象。

浙公网安备 33010602011771号