实验2
实验2:类和对象
四、实验结论
1. 实验任务1:类 T
源代码 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 info: a simple class sample
T objects'max count: 999
T objects'current count: 0
T constructor called.
t1 = (0, 0)
T constructor called.
t2 = (3, 4)
T copy constructor called.
t3 = (6, 8)
T move constructor called.
t4 = (3, 4)
test: T objects'current count: 4
T destructor called.
T destructor called.
T destructor called.
T destructor called.
test: T objects'current count: 0

问题回答
问题1:构造函数和析构函数的作用及调用时机
普通构造函数用来初始化新对象;复制构造函数用已有对象创建新对象;移动构造函数用右值创建新对象。对象生命周期结束时调用析构函数。
t1、t2 调用普通构造函数,t3 调用复制构造函数,t4 调用移动构造函数。本例的移动构造只是复制了整数,t2 的值没有改变。
问题2:将静态成员定义移到头文件后能否编译?
不能。t.cpp 和 task1.cpp 都包含了这个头文件,导致静态成员被定义多次, multiple definition 错误。#pragma once 只能防止一个源文件重复包含头文件,不能解决多个源文件中的重复定义。

问题3:t1 至 t4 的作用域和生命周期
t1 到 t4 从各自声明的位置开始,在内层大括号结束时离开作用域。它们构造成功后一直存在到离开这个代码块,析构顺序和构造顺序相反。m1、m2 是私有成员,不能在类外通过 t1 直接访问,体现了封装和信息隐藏。
问题4:throw 的作用和对象数量达到上限时的情况
throw 用来抛出异常,程序会寻找可以处理这个异常的位置。把 MAX_CNT 改成 2 后,构造 t3 时抛出 runtime_error,因没有捕获,本机运行异常终止且未观察到 t1、t2 的析构输出。没有匹配处理器时,terminate 前是否栈展开由实现决定;若异常被外层处理器捕获,栈展开会析构已完全构造的局部对象,而构造失败的 t3 自身不会析构。参考:cppreference 异常
上限为 2 时的运行记录:
T constructor called.
t1 = (0, 0)
T constructor called.
t2 = (3, 4)
terminate called after throwing an instance of 'std::runtime_error'
what(): T: maximum object count exceeded

2. 实验任务2:复数类 Complex
源代码 Complex.h
点击查看代码
#pragma once
#include <string>
class Complex {
public:
static const std::string doc;
Complex(double real = 0, double imag = 0);
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& 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 real_, imag_;
};
源代码 Complex.cpp
点击查看代码
#include "Complex.h"
#include <cmath>
#include <iostream>
const std::string Complex::doc = "a simplified complex class";
Complex::Complex(double real, double imag): real_(real), imag_(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_ < 0 ? " - " : " + ") << std::abs(c.imag_) << 'i';
}
double abs(const Complex& c) { return std::hypot(c.real_, c.imag_); }
Complex add(const Complex& a, const Complex& b) { return Complex(a.real_ + b.real_, a.imag_ + b.imag_); }
bool is_equal(const Complex& a, const Complex& b) { return a.real_ == b.real_ && a.imag_ == b.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"
void test_Complex() {
using std::cout; using std::endl; using std::boolalpha;
cout << "类成员测试: " << endl << Complex::doc << endl << endl;
cout << "Complex 对象测试: " << endl;
Complex c1, c2(3, -4), c3(c2), c4 = c2;
const Complex c5(3.5), 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 << "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;
}
void test_std_complex() {
using std::cout; using std::endl; using std::boolalpha;
cout << "std::complex<double> 对象测试: " << endl;
std::complex<double> c1, c2(3, -4), c3(c2), c4 = c2, c5 = 3.5;
const std::complex<double> c6(3.5);
cout << "c1 = " << c1 << endl << "c2 = " << c2 << endl;
cout << "c3 = " << c3 << endl << "c4 = " << c4 << endl << "c5 = " << c5 << endl;
cout << "c6.real = " << c6.real() << ", c6.imag = " << c6.imag() << endl << endl;
cout << "复数运算测试: " << endl << "abs(c2) = " << abs(c2) << endl;
c1 += c2;
cout << "c1 += c2, c1 = " << c1 << endl << 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();
}

运行测试及结果
自定义类得到 c2 = 3 - 4i、abs(c2) = 5、c1 == c2 为 true,c4 = 6 - 8i;标准库复数对应结果为 (3,-4)、5、true 和 (6,-8)。
问题1:const 对象和 const 成员函数
real()、imag() 需要声明为 const 成员函数,否则不能通过 const 对象 c6 调用。c6.add(c2) 也无法通过编译,因为 add 需要修改对象,而 c6 是常量对象。题目中“允许再被修改”应为笔误。
问题2:自定义复数类和标准库的使用区别
标准库示例使用 +=、+、==、!=、<<,形式更简洁;运算符重载让类对象可以使用运算符形式调用相应运算符函数。
问题3:友元函数是否必须?
这些友元并非必须:普通非成员函数可通过公开的 real()、imag() 实现相同功能。cppreference 的 std::abs(std::complex) 将其列为非成员函数,接口不要求其为友元;具体实现应查看对应标准库源码。
工业场景中使用 friend 的考虑
在确实需要访问非公开实现,且不能用合理公开接口表达时考虑友元;限制友元数量有助于降低耦合。
3. 实验任务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);
void execute(ControlType cmd) const;
static int get_cnt();
private:
static int total_cnt;
};
源代码 PlayerControl.cpp
点击查看代码
#include "PlayerControl.h"
#include <algorithm>
#include <cctype>
#include <iostream>
int PlayerControl::total_cnt = 0;
PlayerControl::PlayerControl() {}
ControlType PlayerControl::parse(const std::string& control_str) {
std::string lower = control_str;
std::transform(lower.begin(), lower.end(), lower.begin(),
[](unsigned char c) { return static_cast<char>(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;
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(); }
运行测试及结果
输入 play、PAUSE、NeXt、prev、STOP、blah 和 quit,输出分别为播放、暂停、下一首、上一首、停止和未知命令,计数依次为 1 至 6。quit 结束循环;原测试代码只识别小写 quit。

问题回答
问题:const 成员函数中为什么可以修改 total_cnt?
total_cnt 是属于类的静态数据成员。const 成员函数限制通过 this 修改当前对象的非静态成员,但是不阻止修改静态成员,因此 ++total_cnt 合法。
4. 实验任务4:分数类 Fraction
源代码 Fraction.h
点击查看代码
#pragma once
#include <string>
class Fraction {
public:
static const std::string doc;
Fraction(int up, int down = 1);
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;
};
源代码 Fraction.cpp
点击查看代码
#include "Fraction.h"
#include <iostream>
#include <numeric>
#include <stdexcept>
const 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: denominator cannot be zero");
if (down < 0) { up = -up; down = -down; }
int divisor = std::gcd(up, down);
up /= divisor;
down /= divisor;
}
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) { std::cout << f.up << '/' << f.down; }
Fraction add(const Fraction& a, const Fraction& b) { return Fraction(a.up*b.down + b.up*a.down, a.down*b.down); }
Fraction sub(const Fraction& a, const Fraction& b) { return Fraction(a.up*b.down - b.up*a.down, a.down*b.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) { 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 << 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();
}
运行测试及结果
f1 = 5/1
f2 = -3/4
f3 = -3/2
f4 = -3/2
f5 = 3/2
f5.get_up() = 3, f5.get_down() = 2
f1 + f2 = 17/4
f1 - f2 = 23/4
f1 * f2 = -15/4
f1 / f2 = -20/3
f4 + f5 = 0/1
f6 = 42/55
f7 = 0/1
terminate called after throwing an instance of 'std::invalid_argument'
what(): Fraction: denominator cannot be zero

测试代码故意执行除以零分数,构造结果时因分母为零抛出异常;测试代码没有捕获异常,因此本次运行异常终止。
问题回答
问题:分数运算选择哪种方案,为什么?
选择方案1。在方案1中算术函数可直接访问分子、分母,并保持给定测试代码的调用方式。也可以通过公开的 get_up()、get_down() 实现命名空间自由函数,减少对私有成员的直接访问。构造时统一分母符号并按最大公约数约分。
五、实验总结
本次实验练习了类的定义和多文件组织,也接触了构造函数、析构函数、静态成员、友元和 const。编写复数类和分数类时,需要注意哪些数据可以公开、哪些数据需要保护;分数计算还要考虑分母为零的情况。
最后使用了ai协助排版,利用ai理解了部分原理。

浙公网安备 33010602011771号