实验2
任务一
源代码
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 << ")";
}
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类对象数目
};
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
普通构造函数:传入参数,自定义初始化成员 调用时机:直接定义对象、传参初始化新对象时
复制构造函数:用一个已有同类型对象复制出新对象 调用时机:用已有对象初始化新对象、值传递传对象、函数返回对象
移动构造函数:转移临时对象资源,避免拷贝开销 调用时机:用std;:move把左值转为右值来初始化新对象,或者返回临时对象
析构函数:对象销毁时自动调用,释放对象占用的资源 调用时机:对象离开作用域、生命周期结束时自动调用
t1~t4分别触发:普通构造、普通构造、复制构造、移动构造
问题2
程序无法正确编译,报错信息如下

分析:C++中类的静态成员变量必须在类外进行定义和初始化。将定义放到头文件t.h中每一次包含头文件都会生成一份定义,触发多重定义(multiple definition)链接报错。
问题3
t1~t4的作用域局限于test( )函数内的代码块,即下图{ }内区域
生命期:从定义语句创建对象开始,到大括号结束,全部依次调用析构函数销毁。
不能在这个作用域通过t1访问私有成员m1,m2
体现特性:封装性,即类的私有成员只能在类的内部访问,外部代码不可见


问题4
throw的功能:用于抛出异常。当遇到错误时,立即中断当前函数执行,将错误信息向上层传递,交由catch处理。
把MAX_CNT改成2后,程序在尝试创建第3个对象时崩溃了,代码异常终止。
已创建的对象;不会被正常销毁,因为异常未被try-catch捕获,程序直接调用std::terminate终止了整个进程,导致栈展开机制终端,没有机会执行t1和t2的析构函数。

任务二
源代码
Complex.h
#ifndef COMPLEX_H
#define COMPLEX_H
#include <string>
#include <iostream>
class Complex{
public:
static const std::string doc;
Complex();
Complex(double r,double i = 0.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& 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);
private:
double real_part;
double imag_part;
};
#endif
Complex.cpp
#include "Complex.h"
#include <cmath>
const std::string Complex::doc = "a simplified complex class";
Complex::Complex() : real_part(0.0),imag_part(0.0){}
Complex::Complex(double r,double i) : real_part(r),imag_part(i){}
double Complex::real() const{ return real_part; }
double Complex::imag() const{ return imag_part; }
void Complex::add(const Complex& other){
real_part += other.real_part;
imag_part += other.imag_part;
}
void output(const Complex& c){
std::cout << c.real_part;
if(c.imag_part >= 0){
std::cout << " + " << c.imag_part << "i";
} else{
std::cout << " - " << -c.imag_part << "i";
}
}
double abs(const Complex& c) {
return std::sqrt(c.real_part*c.real_part+c.imag_part*c.imag_part);
}
Complex add(const Complex& c1,const Complex& c2) {
return Complex(c1.real_part+c2.real_part,c1.imag_part+c2.imag_part);
}
bool is_equal(const Complex& c1, const Complex& c2) {
return(c1.real_part == c2.real_part) && (c1.imag_part == c2.imag_part);
}
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;
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
①必须加上const关键词,否则编译器会报错,提示”将‘ const Complex '作为’ this '参数传递会丢弃限定符。
②不能编译通过,因为c6是const对象,,而add成员函数会修改对象的成员变量,const对象只能调用const成员函数。这体现了类的数据保护机制。
问题2
标准库模板类更简洁。自定义类需要写add(c1,c2)、is_equal(c1,c2),而标准库可以直接写 c1+c2、c1==c2。由此推断出运算符本质上就是函数,运算符重载就是给特定的函数绑定运算符符号,让调用形式更简洁自然。
问题3
①不是必须的,但用友元函数可以保持类的封装性。
替代方案:给Complex类提供public的getter接口,output、abs、add等函数通过调用公有接口读取实部、虚部,不再直接访问私有成员,通过公有接口完成计算与输出。
②std::complex没有把abs设为友元,它是独立的非成员模板函数,依靠公有访问接口获取数据,不需要友元权限。
链接地址:https://cppreference.cn/w/cpp/numeric/complex
③在工业级C++开发中,friend函数的使用极为克制且通常遵循严格的规范。在某些核心场景例如需要访问私有数据但不想破坏封装时会使用friend。遵循原则:非必要不用,优先通过公共接口实现,仅在保持接口狭窄或需要极致性时使用。
任务三
源代码
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;
} else if(str == "pause"){
return ControlType::Pause;
} else if(str == "next"){
return ControlType::Next;
} else if(str == "prev"){
return ControlType::Prev;
} else if(str == "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;
}
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.h的类定义中,total_cnt被声明为了static int total_cnt,及静态成员变量。const成员函数的约束是不能修改该类的非静态成员变量,而静态成员属于整个类,不受const成员函数“不可修改”规则的限制。
任务四
源代码
Fraction.h
#pragma once
#include <string>
#include <stdexcept>
class Fraction {
private:
int up;
int down;
void simplify();
public:
static const std::string doc;
Fraction(int u = 0, int d = 1);
int get_up() const { return up; }
int get_down() const { return down; }
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);
};
Fraction.cpp
#include "Fraction.h"
#include <iostream>
const std::string Fraction::doc =
"Fraction类 v 0.01版.\n"
"目前仅支持分数对象的构造、输出、加/减/乘/除运算.";
int gcd(int a, int b) {
a = (a < 0) ? -a : a;
b = (b < 0) ? -b : b;
while (b != 0) {
int t = b;
b = a % b;
a = t;
}
return a;
}
void Fraction::simplify() {
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 u, int d) : up(u), down(d) {
if (down == 0) {
throw std::invalid_argument("Fraction: 分母不能为0");
}
simplify();
}
Fraction Fraction::negative() const {
Fraction temp(-up, down);
return temp;
}
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) {
Fraction res(f1.up * f2.down + f2.up * f1.down, f1.down * f2.down);
return res;
}
Fraction sub(const Fraction& f1, const Fraction& f2) {
Fraction res(f1.up * f2.down - f2.up * f1.down, f1.down * f2.down);
return res;
}
Fraction mul(const Fraction& f1, const Fraction& f2) {
Fraction res(f1.up * f2.up, f1.down * f2.down);
return res;
}
Fraction div(const Fraction& f1, const Fraction& f2) {
if (f2.up == 0) {
throw std::invalid_argument("Fraction: 除数不能为0");
}
Fraction res(f1.up * f2.down, f1.down * f2.up);
return res;
}
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:分数类+友元函数
理由:
1、效率高:加减乘除运算需要频繁直接读取两个分数的私有成员,友元函数可以直接访问,省去了频繁调用get_up( )等接口的开销。
2、代码简洁:避免了在类中定义大量仅用于运算的数据访问接口,让代码更易读和维护。
实验总结
通过四个实验,我深刻理解了面向对象最重要的封装与数据保护机制:将核心数据私有隐藏,仅通过可控公有接口对外提供服务,有效避免非法复制与数据破坏,提升了程序稳定性与可维护性。同时熟悉了多文件编程结构,养成了声明与实现分离的规范编码习惯,
浙公网安备 33010602011771号