实验2 类和对象_基础编程
任务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;
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
line7 普通构造函数 初始化对象 为成员变量赋初始值 在创建对象是调用
line8 复制构造函数 使用一个已存在的对象初始化一个新对象 执行的是“深拷贝“或”浅拷贝“ 当同类型对象进行初始化是调用
line9 移动构造函数 通过临时对象的资源来初始化新对象 当使用优质初始化新对象时调用
line10 析构函数 释放对象战役的资源 对象生命周期结束时自动调用 - 问题2
可以进行编译 ???
![image]()
- 问题3
t1-t4都是定义在test()函数内的局部作用域 是能在定义他们的{}被访问 他们的生命周期从定义声明出开始 一直持持续到最内层}结束 当执行到}时 析构函数自动调用 顺序与构造相反 t4->t3->t2->t1
不能通过t1访问其私有成员m1,m2 若写t1.m1或t2.m2会编译错误 体现了类的封装性 - 问题4
throw 是 C++ 的异常抛出关键字。当程序运行到 if 条件成立(即当前对象计数达到了最大值 MAX_CNT)时,throw std::runtime_error("...") 会立即中断当前构造函数的执行,并向上层调用栈抛出异常,直到找到匹配的 catch 块来处理它。
![image]()
崩溃了 已经创建的对象不会正常销毁 因为看到两个T constructor called. 却没有看到T destructor called.
任务2
项目源代码
- task2.cpp
#include <iostream>
#include <string>
#include <cmath>
#include <complex>
class Complex {
public:
static const std::string doc;
Complex(double r = 0.0, double i = 0.0);
Complex(const Complex& c);
double real() const;
double imag() const;
void add(const Complex& c);
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_;
double imag_;
};
const std::string Complex::doc = "a simplified complex class";
Complex::Complex(double r, double i) : real_{r}, imag_{i} {}
Complex::Complex(const Complex& c) : real_{c.real_}, imag_{c.imag_} {}
double Complex::real() const { return real_; }
double Complex::imag() const { return imag_; }
void Complex::add(const Complex& c) {
real_ += c.real_;
imag_ += c.imag_;
}
void output(const Complex& c) {
std::cout << c.real_;
if (c.imag_ >= 0) std::cout << "+";
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& c1, const Complex& c2) {
return Complex(c1.real_ + c2.real_, c1.imag_ + c2.imag_);
}
bool is_equal(const Complex& c1, const Complex& c2) {
return (c1.real_ == c2.real_) && (c1.imag_ == c2.imag_);
}
bool is_not_equal(const Complex& c1, const Complex& c2) {
return !is_equal(c1, c2);
}
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()能编译通过,real() 和 imag() 这两个成员函数的声明和定义末尾都必须加上 const 关键字
如果不加 则编译错误
![image]()
将const Complex 作为this参数传递 丢弃了限定符
不能 add是非const成员函数 他的功能会修改real_ 和imag_ 而c6是const对象 限定不能修改 体现了类的const保护机制 -
问题2
标准库 std::complex的用法更简洁
从表格可以看出,标准库直接使用运算符(+=、+、==、!=)和流输出(<<),而自定义类需要写成命名函数(add、is_equal、output)功能上是对应的 -
问题3
1,不是必须的 思路:为 Complex 类添加公有的 原代码已有的 real() 和 imag()。然后 output、abs、add 这些非成员函数不再直接访问 private 的 real_ /和imag_,而是通过调用 c.real() 和 c.imag() 来获取数据。
2,不是友元。std::abs(std::complex) 是一个在 std 命名空间中声明的普通函数模板,其声明形式为 templateT abs(const complex & z);。它通过 std::complex 的公有成员函数 real() 和 imag() 来获取实部和虚部进行计算,并未被声明为 complex 类的友元。
3,优先用公有接口。仅当运算符重载(如 operator<<、operator+)需要对称语法,且通过公有 getter 访问会导致性能热点或代码臃肿时,才考虑 friend。friend 是显式的封装“后门”,滥用会破坏封装,但在必须让非成员函数拥有与成员同等访问权以保持接口自然时,它是合理的设计取舍。
任务3
项目源代码
- 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;
for(char& c : s) {
c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
}
if (s == "play") return ControlType::Play;
if (s == "pause") return ControlType::Pause;
if (s == "next") return ControlType::Next;
if (s == "prev") return ControlType::Prev;
if (s == "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;
}
- 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();
}
运行测试

问题
因为 total_cnt是static静态成员变量,它不属于任何一个对象,而是属于类本身
任务4
源代码
- Fraction.h
#pragma once
#include <string>
#include <iostream>
class Fraction {
public:
static const std::string doc;
Fraction(int up0 = 0, int down0 = 1);
Fraction(const Fraction& other);
int get_up() const;
int get_down() const;
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);
private:
int up;
int down;
void simplify();
};
- Fraction.cpp
#include <stdexcept>
#include <cmath>
const std::string Fraction::doc =
"Fraction类 v 0.01版.\n"
"目前仅支持分数对象的构造、输出、加/减/乘/除运算.";
int my_gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
Fraction::Fraction(int up0, int down0) : up{up0}, down{down0} {
if (down == 0) {
throw std::invalid_argument("Fraction: 分母不能为0");
}
simplify();
}
Fraction::Fraction(const Fraction& other) : up{other.up}, down{other.down} {}
void Fraction::simplify() {
if (up == 0) {
down = 1;
return;
}
if (down < 0) {
up = -up;
down = -down;
}
int gcd_val = my_gcd(std::abs(up), down);
up /= gcd_val;
down /= gcd_val;
}
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& f1, const Fraction& f2) {
int new_up = f1.up * f2.down + f2.up * f1.down;
int new_down = f1.down * f2.down;
return Fraction(new_up, new_down);
}
Fraction sub(const Fraction& f1, const Fraction& f2) {
int new_up = f1.up * f2.down - f2.up * f1.down;
int new_down = f1.down * f2.down;
return Fraction(new_up, new_down);
}
Fraction mul(const Fraction& f1, const Fraction& f2) {
int new_up = f1.up * f2.up;
int new_down = f1.down * f2.down;
return Fraction(new_up, new_down);
}
Fraction div(const Fraction& f1, const Fraction& f2) {
if (f2.up == 0) {
throw std::invalid_argument("Fraction: 分母不能为0");
}
int new_up = f1.up * f2.down;
int new_down = f1.down * f2.up;
return Fraction(new_up, new_down);
}
- task4.cpp
#include <iostream>
#include "Fraction.h"
#include <stdexcept>
int main() {
std::cout << "测试1: Fraction类基础功能测试" << std::endl;
std::cout << "Fraction类测试:" << std::endl;
std::cout << Fraction::doc << std::endl;
std::cout << std::endl;
// 构造测试
Fraction f1(5); // 5/1
Fraction f2(-3, 4); // -3/4
Fraction f3(-3, 2); // -3/2
Fraction f4(f3); // 拷贝构造 -3/2
Fraction f5(-6, -4); // 3/2 (测试化简)
std::cout << "f1 = "; output(f1); std::cout << std::endl;
std::cout << "f2 = "; output(f2); std::cout << std::endl;
std::cout << "f3 = "; output(f3); std::cout << std::endl;
std::cout << "f4 = "; output(f4); std::cout << std::endl;
std::cout << "f5 = "; output(f5); std::cout << std::endl;
std::cout << "f5.get_up() = " << f5.get_up() << ", f5.get_down() = " << f5.get_down() << std::endl;
// 运算测试
std::cout << "f1 + f2 = "; output(add(f1, f2)); std::cout << std::endl;
std::cout << "f1 - f2 = "; output(sub(f1, f2)); std::cout << std::endl;
std::cout << "f1 * f2 = "; output(mul(f1, f2)); std::cout << std::endl;
std::cout << "f1 / f2 = "; output(div(f1, f2)); std::cout << std::endl;
std::cout << "f4 + f5 = "; output(add(f4, f5)); std::cout << std::endl;
std::cout << std::endl;
// 测试2: 分母为0测试
std::cout << "测试2: 分母为0测试:" << std::endl;
Fraction f6(42, 55);
Fraction f7(0); // 0/1
std::cout << "f6 = "; output(f6); std::cout << std::endl;
std::cout << "f7 = "; output(f7); std::cout << std::endl;
std::cout << "f6 / f7 = ";
try {
output(div(f6, f7));
std::cout << std::endl;
} catch (const std::invalid_argument& e) {
// 为了复刻图片中的 terminate called after throwing an instance... 的输出效果
// 这里重新抛出异常,让程序终止并打印标准错误信息
throw;
}
return 0;
}
运行测试

问题
我选择的是 方案1:分数类 + 友元函数
分数运算(加、减、乘、除)和输出(output)需要频繁且直接地读取分子 up 和分母 down。将它们声明为 friend(友元函数),这些函数可以直接访问对象的私有属性。




浙公网安备 33010602011771号