实验二
实验任务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;
}
}
int main() {
std::cout << "test Class T: \n";
test();
T t2(1, 2);
T t3(t2); // 复制构造
t3.adjust(2);
std::cout << "t3 = "; output(t3); std::cout << std::endl;
T t4(std::move(t2)); // 移动构造
std::cout << "t4 = "; output(t4); std::cout << std::endl;
std::cout << "test: T objects' current count: " << T::get_cnt() << std::endl;
return 0;
}
问题1:各构造函数、析构函数的功能、调用时机,及 t1–t4 触发情况
| 函数 | 功能 | 调用时机 | 本任务触发 |
|---|---|---|---|
T(int x = 0, int y = 0) 普通构造 |
用实参初始化新对象的 m1、m2,对象计数 +1 |
定义并初始化一个新对象时 | t1(默认参数)、t2(3,4)、main 中的 t2(1,2) |
T(const T &t) 复制构造 |
用同类型已有对象逐个拷贝成员,计数 +1 | 用已有对象初始化另一个新对象(值复制、传值/复制初始化)时 | T t3(t2) |
T(T &&t) 移动构造 |
接管右值对象的资源(本例为拷贝成员),计数 +1 | 用即将销毁的右值对象初始化新对象,配合 std::move |
T t4(std::move(t2)) |
~T() 析构 |
清理对象、计数 -1 | 对象离开作用域或被 delete 时自动调用 |
每个对象块结束/函数返回时自动触发 |
补充:t1、t2 在内层 {} 块结束时析构;t3、t4 在 main 结束时析构。
问题2:把静态成员定义(line8–10)剪切到 t.h 末尾,能否编译?
不能正确完成链接。
static成员属于类而非某个对象,必须在类外定义并分配一次内存;头文件会被多个翻译单元(t.cpp、task1.cpp)包含。- 若把定义写进头文件,每个包含它的
.cpp都会生成一份定义,违反 ODR(一次定义规则),链接时报multiple definition of T::doc / T::MAX_CNT / T::current_cnt。 - 例外:
const静态整型成员可在类内初始化;但std::string这类仍必须类外定义。 - 正确做法:声明放头文件,定义放 t.cpp。
问题3:t1–t4 的作用域、生命期;能否访问私有成员;体现什么特性
t1、t2:作用域和生命期限于test()内的内层{}块,从定义处到块结束,块结束自动析构。t3、t4:作用域和生命期在 main 函数内,从定义到 main 结束。- 不能通过
t1直接访问私有成员m1、m2,编译器报访问权限错误('m2' is private within this context)。 - 体现了类的封装与信息隐藏:内部数据私有,只能通过公有接口访问,外部不能随意读写。
问题4:throw 的作用;MAX_CNT 改成 2 后的行为;已构造对象是否正常销毁
throw:抛出一个异常对象,中断当前函数执行,沿调用栈向上查找匹配的catch;找不到则调用std::terminate终止程序。本例抛出std::runtime_error。- 把
MAX_CNT改为 2 后:第 3 个对象构造时计数达到上限,构造函数throw;程序未捕获该异常,异常终止(崩溃/非正常结束)。 - 已成功构造的局部对象会被正常销毁:异常发生时栈展开(stack unwinding)会沿调用栈回溯,对已构造的局部对象调用析构函数(RAII);但尚未构造完成的对象不会被析构。全局/静态对象在
terminate后的销毁行为不做保证。
实验任务2
源代码
点击查看代码
#pragma once
#include <string>
class Complex {
public:
static const std::string doc; // 类说明,常量,公有
Complex(double re = 0, double im = 0);
Complex(const Complex &other) = default;
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_; // 实部、虚部,私有
};
点击查看代码
#include "Complex.h"
#include <cmath>
#include <iostream>
const std::string Complex::doc{"a simplified Complex class"};
Complex::Complex(double re, double im) : real_{re}, imag_{im} {}
double Complex::real() const { return real_; }
double Complex::imag() const { return imag_; }
void Complex::add(const Complex &other) {
real_ += other.real_;
imag_ += other.imag_;
}
// 友元:以 a+bi 形式输出
void output(const Complex &c) {
std::cout << c.real_;
if (c.imag_ >= 0) {
std::cout << " + " << c.imag_ << "i";
} else {
std::cout << " - " << -c.imag_ << "i";
}
}
// 友元:取模
double abs(const Complex &c) {
return std::sqrt(c.real_ * c.real_ + c.imag_ * 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);
}
点击查看代码
#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 Complex对象上调用,成员函数声明后必须加const限定(写在参数列表后):
double real() const;
double imag() const;
不加 const 时,编译器报错大意:'this' argument to member function 'real' has type 'const Complex', but function is not const(不能把 const 对象传给非 const 成员函数,丢弃了 const 限定)。
- 添加
c6.add(c2)编译不通过。add()是会修改对象的非 const 成员函数,而c6是 const 对象,不允许调用非 const 成员去修改它。这体现了类的 const 数据保护机制:const 对象只能读、不能被修改,编译期阻止非法写操作。
问题2:两种用法比较,函数与运算的内在关联
- 标准库
std::complex<T>用法更简洁:直接用+=、+、==、!=、<<等运算符。 - 运算符本质上是带特殊名字的函数(运算符重载),标准库把加法、比较、输出封装成运算符重载;自定义类也可以提供同名运算符达到同样写法。两者内在关联:运算符是函数的语法糖,底层仍是函数调用,标准库只是把常用运算重载成了运算符形式。
| 自定义 Complex | 标准库 std::complex |
|---|---|
c1.add(c2) |
c1 += c2 |
c4 = add(c2, c3) |
c4 = c2 + c3 |
is_equal(c1, c2) |
c1 == c2 |
is_not_equal(c1, c2) |
c1 != c2 |
output(c1) |
cout << c1 |
abs(c2) |
abs(c2) |
问题3
-
不是必须设为友元。 只要类提供
real()、imag()等公有只读接口,普通非成员自由函数完全可以通过这些公有接口拿到实部、虚部完成output / abs / add,不需要访问私有成员,也就不需要friend。只有当函数必须直接读写非公有成员、且无法通过公有接口表达时,才需要友元。 -
标准库
std::complex的abs不是友元,它是非成员函数,通过公开的real()/imag()接口取值。 -
工业界何时用 friend(150 字内):友元会破坏封装、增加耦合,只在确有必要时使用——当某个函数(或类)必须直接访问非公有成员,且该访问无法通过现有公有接口合理实现时,才授予友元权限;能靠公有接口完成的运算一律写成普通自由函数。优先用接口组合,慎用友元,控制暴露面。
实验任务3
源代码
点击查看代码
#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; // 操作总次数
};
点击查看代码
#include "PlayerControl.h"
#include <cctype>
#include <iostream>
int PlayerControl::total_cnt = 0;
PlayerControl::PlayerControl() {}
// 大小写不敏感地把命令串解析为枚举值
ControlType PlayerControl::parse(const std::string& control_str) {
std::string low;
for (char ch : control_str) {
low += static_cast<char>(std::tolower(static_cast<unsigned char>(ch)));
}
if (low == "play") return ControlType::Play;
if (low == "pause") return ControlType::Pause;
if (low == "next") return ControlType::Next;
if (low == "prev") return ControlType::Prev;
if (low == "stop") return ControlType::Stop;
return ControlType::Unknown;
}
void PlayerControl::execute(ControlType cmd) const {
++total_cnt; // 静态成员不属于当前对象,const 成员函数仍可修改
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;
}
点击查看代码
#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();
}
问题:execute 是 const 成员函数,为什么内部允许 ++total_cnt?
total_cnt 是 static 静态成员,属于整个类,不属于某个具体对象,不占用对象的存储空间。const 成员函数限制的是不能修改当前对象(*this)的非静态成员,静态成员不受此限制,因此 const 的 execute 内部仍然可以 ++total_cnt。
实验任务4
源代码
点击查看代码
#pragma once
#include <string>
class Fraction {
public:
static const 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; // 求负,对象本身不变,返回新分数
private:
int up, down; // 分子、分母,私有
void normalize(); // 内部工具:约分、符号归到分子
};
// 自由函数(方案2:命名空间/非友元自由函数,通过公有接口访问)
void output(const Fraction &f);
Fraction add(const Fraction &a, const Fraction &b);
Fraction sub(const Fraction &a, const Fraction &b);
Fraction mul(const Fraction &a, const Fraction &b);
Fraction div(const Fraction &a, const Fraction &b);
点击查看代码
#include "Fraction.h"
#include <cmath>
#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 (down0 == 0) {
throw std::invalid_argument("Fraction: 分母不能为0");
}
normalize();
}
int Fraction::get_up() const { return up; }
int Fraction::get_down() const { return down; }
Fraction Fraction::negative() const {
return Fraction(-up, down);
}
void Fraction::normalize() {
// 符号统一放在分子上
if (down < 0) {
up = -up;
down = -down;
}
int g = std::gcd(std::abs(up), std::abs(down));
if (g == 0) g = 1;
up /= g;
down /= g;
}
void output(const Fraction &f) {
if (f.get_down() == 1) {
std::cout << f.get_up();
} else {
std::cout << f.get_up() << "/" << f.get_down();
}
}
Fraction add(const Fraction &a, const Fraction &b) {
return Fraction(a.get_up() * b.get_down() + b.get_up() * a.get_down(),
a.get_down() * b.get_down());
}
Fraction sub(const Fraction &a, const Fraction &b) {
return Fraction(a.get_up() * b.get_down() - b.get_up() * a.get_down(),
a.get_down() * b.get_down());
}
Fraction mul(const Fraction &a, const Fraction &b) {
return Fraction(a.get_up() * b.get_up(),
a.get_down() * b.get_down());
}
Fraction div(const Fraction &a, const Fraction &b) {
return Fraction(a.get_up() * b.get_down(),
a.get_down() * b.get_up());
}
点击查看代码
#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();
}

浙公网安备 33010602011771号