实验二
task1
源代码
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();
}
运行结果截图:

问题1:
- 普通构造函数 功能:新建对象,初始化成员 m1、m2。 调用时机:直接定义对象、传入整型参数构造对象。
- 拷贝构造函数 功能:用一个已有对象复制出新对象。 调用时机:用已有对象初始化新对象。
- 移动构造函数 功能:接管右值对象的数据,不做深拷贝。 调用时机:使用右值(
std::move转换后的对象、临时对象)初始化新对象。 - 析构函数 功能:对象销毁前清理资源,对象计数减一。 调用时机:对象离开作用域、生命周期结束时自动调用。
T1普通构造函数
T2普通构造函数
T3拷贝构造函数
T4移动构造函数
问题2:

可以跑通
原因分析:本次测试环境下,实际参与编译的只有一个源文件,头文件t.h仅被这一个 cpp 文件展开一次,静态成员只生成一份实体,链接不会出现重复符号,所以可以运行。 但该写法不符合 C++ 单一定义规则 ODR,不具备通用性。
问题3:
t1、t2、t3、t4 是在 test 函数内部的代码块中定义的局部对象:
- 作用域:仅限于它们所在的代码块(大括号
{}内部),出了这个大括号就无法访问。 - 生命周期:程序执行到对象定义语句时,调用构造函数创建对象;当代码执行离开这个大括号(代码块结束)时,自动调用析构函数销毁对象,释放内存。
不能通过 t1 直接访问私有成员 m1、m2。 test()是普通全局函数,既不是类 T 的成员函数,也不是 T 的友元。私有成员m1,m2只允许 T 的成员函数和友元函数(本例output)访问,外部普通函数无法直接访问,体现类的封装与信息隐藏。
问题4:

throw用于主动抛出异常。当待创建对象数量达到上限 MAX_CNT 时,抛出std::runtime_error类型异常,停止构造,阻止新对象生成,提示对象数目超限,实现运行时错误保护。
task2:
complex.h
#pragma once
#include <string>
#include <iostream>
class Complex
{
private:
double m_real;
double m_imag;
public:
// 构造函数
Complex();
Complex(double r);
Complex(double r, double i);
Complex(const Complex& other);
// const成员,供const对象调用
double real() const;
double imag() const;
// 成员函数:this += c
void add(const Complex& c);
static const std::string doc;
// 友元声明
friend void output(const Complex& c);
friend double abs(const Complex& c);
friend bool is_equal(const Complex& a, const Complex& b);
friend bool is_not_equal(const Complex& a, const Complex& b);
friend Complex add(const Complex& a, const Complex& b);
};
complex.cpp
#include "Complex.h"
#include <cmath>
#include <iomanip>
//静态常量类外初始化
const std::string Complex::doc = "A self?defined complex number class";
Complex::Complex() : m_real{0}, m_imag{0}
{
}
Complex::Complex(double r) : m_real{r}, m_imag{0}
{
}
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;
}
// 成员add:自身加上c
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 << ", " << c.m_imag << "i)";
}
double abs(const Complex& c)
{
return std::sqrt(c.m_real*c.m_real + c.m_imag*c.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);
}
//全局add,a+b返回新对象
Complex add(const Complex& a, const Complex& b)
{
return Complex{a.m_real + b.m_real, a.m_imag + b.m_imag};
}
运行截图:


问题1:需要给 real()、imag() 成员函数末尾加 const 关键字。
不加的报错:不能在 const 对象上调用非 const 成员函数。
c6.add(c2); 不能编译通过。 add()成员函数会修改调用对象本身(修改实部虚部),它是非 const 成员函数;而c6是const常量对象,C++ 禁止 const 对象调用会修改自身的成员函数。 体现的保护机制:const 常量对象保护机制,保证被const 修饰的对象的数据在初始化之后不会被修改。
问题2:std::complex<T>(标准库模板)使用形式更简洁
运算符本质上就是特殊的函数。标准库是通过运算符重载,把+、+=、==、!=、流输出<<这些运算符映射到对应的函数实现上,只是语法换成了我们数学上熟悉的运算符写法,可读性更强。
问题3:1.不是必须设为友元。 可以改成普通非成员函数:依靠类里提供的real()、imag()这两个 public 成员函数读取实部、虚部,不需要直接访问私有成员,就能实现 output、abs、add 同样的功能。 思路:函数内部调 用 c.real()、c.imag()获取数值进行计算,输出。
2.std::complex的 abs不是友元函数,它是独立的非成员函数,通过 public 接口获取实虚部。 cppreference 链接:https://en.cppreference.com/w/cpp/numeric/complex/abs
3.friend 会破坏封装,工业上尽量少用。仅当函数需要高效访问类私有成员、又不适合作为成员函数时才使用,比如运算符重载、需要同时操作多个不同类对象的函数。优先使用 public 接口,能用成员函数 / 公开接口实现就不使用友元。
task3:
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;
};
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();
}
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(), ::tolower);
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;
}
运行截图:

const 成员函数仅禁止修改本对象的非静态成员;total_cnt 是类的静态成员,不属于对象,因此可以修改。
task4:
Fraction.h
#pragma once
#include <string>
class Fraction
{
private:
int up;
int down;
int gcd(int a, int b) const;
void reduce();
public:
Fraction(int num = 0, int den = 1);
Fraction(const Fraction& other);
Fraction negative() const;
int get_up() const;
int get_down() const;
static const std::string doc;
};
namespace frac
{
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);
}
Fraction.cpp
#include "Fraction.h"
#include <iostream>
#include <stdexcept>
#include <cstdlib>
const std::string Fraction::doc = "Fraction类 v 0.01版.\n目前仅支持分数对象的构造、输出、加/减/乘/除运算.";
int Fraction::gcd(int a, int b) const
{
a = std::abs(a);
b = std::abs(b);
while(b != 0)
{
int t = b;
b = a % b;
a = t;
}
return a;
}
void Fraction::reduce()
{
if(down == 0)
{
throw std::invalid_argument("Fraction: 分母不能为0");
}
if(down < 0)
{
up = -up;
down = -down;
}
int g = gcd(up, down);
if(g != 0)
{
up /= g;
down /= g;
}
if(up == 0)
{
down = 1;
}
}
Fraction::Fraction(int num, int den): up{num}, down{den}
{
reduce();
}
Fraction::Fraction(const Fraction& other): up{other.up}, down{other.down}
{}
Fraction Fraction::negative() const
{
return Fraction(-up, down);
}
int Fraction::get_up() const
{
return up;
}
int Fraction::get_down() const
{
return down;
}
namespace frac
{
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)
{
int nu = a.get_up()*b.get_down() + b.get_up()*a.get_down();
int nd = a.get_down() * b.get_down();
return Fraction(nu, nd);
}
Fraction sub(const Fraction& a, const Fraction& b)
{
int nu = a.get_up()*b.get_down() - b.get_up()*a.get_down();
int nd = a.get_down() * b.get_down();
return Fraction(nu, nd);
}
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());
}
}
task4.cpp
#include <iostream>
#include "Fraction.h"
void test1()
{
using std::cout;
using std::endl;
cout << "Fraction类测试:" << endl << endl;
cout << Fraction::doc << endl << endl;
Fraction f1(5);
Fraction f2(3, -4);
Fraction f3(-18, 12);
Fraction f4(f3);
cout << "f1 = "; frac::output(f1); cout << endl;
cout << "f2 = "; frac::output(f2); cout << endl;
cout << "f3 = "; frac::output(f3); cout << endl;
cout << "f4 = "; frac::output(f4); cout << endl;
const Fraction f5(f4.negative());
cout << "f5 = "; frac::output(f5); cout << endl;
cout << "f5.get_up() = " << f5.get_up()
<< ", f5.get_down() = " << f5.get_down() << endl;
cout << "f1 + f2 = "; frac::output(frac::add(f1,f2)); cout << endl;
cout << "f1 - f2 = "; frac::output(frac::sub(f1,f2)); cout << endl;
cout << "f1 * f2 = "; frac::output(frac::mul(f1,f2)); cout << endl;
cout << "f1 / f2 = "; frac::output(frac::div(f1,f2)); cout << endl;
cout << "f4 + f5 = "; frac::output(frac::add(f4,f5)); cout << endl;
}
void test2()
{
using std::cout;
using std::endl;
cout << endl << "测试2:分母为0测试:" << endl;
Fraction f6(42, 55);
Fraction f7(0, 3);
cout << "f6 = "; frac::output(f6); cout << endl;
cout << "f7 = "; frac::output(f7); cout << endl;
cout << "f6 / f7 = "; frac::output(frac::div(f6,f7)); cout << endl;
}
int main()
{
test1();
test2();
return 0;
}
运行截图:

选择方案 2:分数类 + 命名空间自由函数。理由:不使用友元,不破坏类封装;将一组分数运算函数收纳在 frac 命名空间,防止名字污染,类与运算逻辑解耦,结构清晰,便于扩展。
浙公网安备 33010602011771号