实验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();
}
- 运行测试截图
![image]()
- 问题一
普通构造函数用于对象创建并初始化成员数据,复制构造函数利用已存在的对象初始化新对象,移动构造函数通过右值引用暂存临时对象资源以避免不必要的深拷贝,析构函数用于对象生命周期结束时释放资源;t1,t2触发了普通构造函数,t3(t2)触发了复制构造函数,t4(std::move(t2))由于使用了std::move转换为右值,触发了移动构造函数。 - 问题二
不能正确编译,会发生多重定义错误。
![image]()
因为 t.h 同时被 task1.cpp 和 t.cpp 包含了(#include "t.h"),把这两个文件链接合成一个程序时,系统发现有两个同名变量,不知道用哪个,所以报“多重定义”错误。 - 问题三
在测试函数中,t1-t4位于大括号{}构成的局部代码块内,其作用域和生命期在该代码块结束时同步结束;在此作用域内,无法通过t1直接访问其私有成员m1和m2,只能通过公有接口如进行访问,这体现了类的封装特性,将数据私有化以实施保护让外界无法轻易改变。 - 问题四
将MAX_CNT修改为2后,由于对象创建超过上限,触发terminate called after throwing an instance of 'std::runtime_error'
what(): T: maximum object count exceeded.
![image]()
任务2
- 源代码complex.h
点击查看代码
#pragma once
#include <string>
class Complex {
public:
static const std::string doc;
Complex(double r = 0.0, double i = 0.0);
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 m_real;
double m_imag;
};
点击查看代码
#include "Complex.h"
#include <iostream>
#include <cmath>
const std::string Complex::doc = "a simplified Complex class";
Complex::Complex(double r, double i) : m_real(r), m_imag(i) {}
double Complex::real() const {
return m_real;
}
double Complex::imag() const {
return m_imag;
}
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;
if (c.m_imag >= 0) {
std::cout << " + " << c.m_imag << "i";
} else {
std::cout << " - " << -c.m_imag << "i";
}
}
double abs(const Complex& c) {
return std::sqrt(c.m_real * c.m_real + c.m_imag * c.m_imag);
}
Complex add(const Complex& c1, const Complex& c2) {
return Complex(c1.m_real + c2.m_real, c1.m_imag + c2.m_imag);
}
bool is_equal(const Complex& c1, const Complex& c2) {
return (c1.m_real == c2.m_real) && (c1.m_imag == c2.m_imag);
}
bool is_not_equal(const Complex& c1, const Complex& c2) {
return !is_equal(c1, c2);
}
点击查看代码
#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();
}
-
运行测试截图
![image]()
-
问题一
为了让const Complex c6(3.5);调用成员函数,在设计Complex类时必须将real()和imag()声明为常成员函数,即在函数参数列表后加上const关键字,若不添加,编译器会报错passing 'const Complex' as 'this' argument discards qualifiers.若在代码中添加c6.add(c2)则无法编译,因为add()方法会修改对象内部数据,而c6作为const对象无法被修改。 -
问题二
标准库类模板std::complex的运算符重载形式比自定义类的函数调用更简洁,两者存在内在关联,C++中的运算符重载本质上是对函数调用的封装。 -
问题三
将friend void output(const T &t)等设为友元并非必须,若不使用friend,可通过在类中提供公有的get_real()方法,在非成员函数中调用这些接口获取数据。标准库中的std::abs并非友元函数。
任务三
- 源代码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;
};
点击查看代码
#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) {
// xxx
}
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;
}
点击查看代码
#include <iostream>
#include <string>
#include <algorithm>
enum class ControlType { Play, Pause, Next, Prev, Stop, Unknown };
class PlayerControl {
public:
static int total_cnt;
ControlType parse(const std::string& str) {
std::string s = str;
std::transform(s.begin(), s.end(), s.begin(), ::tolower);
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 execute(ControlType cmd) const {
++total_cnt;
if (cmd == ControlType::Play) std::cout << "[play] Playing music...\n";
else if (cmd == ControlType::Pause) std::cout << "[pause] Music paused\n";
else if (cmd == ControlType::Next) std::cout << "[Next] Skipping to next track\n";
else if (cmd == ControlType::Prev) std::cout << "[prev] Back to previous track\n";
else if (cmd == ControlType::Stop) std::cout << "[Stop] Music stopped\n";
}
static int get_cnt() { return total_cnt; }
};
int PlayerControl::total_cnt = 0;
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;
controller.execute(controller.parse(control_str));
std::cout << "Current Player control: " << PlayerControl::get_cnt() << "\n\n";
}
}
int main() { test(); }
- 运行测试截图
![image]()
- 问题
execute(ControlType cmd)const被声明为const成员函数,其语义是承诺不修改该类对象自身的非静态成员变量,但在内部允许执行++total_cnt,是因为total_cnt是声明为static的成员变量,它不受const修饰this指针的限制。
任务四
- 源代码Fraction.h
点击查看代码
#pragma once
#include <string>
#include <iostream>
namespace frac {
class Fraction {
public:
static const std::string doc;
Fraction(int u = 0, int d = 1);
int get_up() const;
int get_down() const;
friend void output(const Fraction& f);
friend Fraction operator+(const Fraction& f1, const Fraction& f2);
friend Fraction operator-(const Fraction& f1, const Fraction& f2);
friend Fraction operator*(const Fraction& f1, const Fraction& f2);
friend Fraction operator/(const Fraction& f1, const Fraction& f2);
private:
int up;
int down;
static int gcd(int a, int b);
};
}
点击查看代码
#include "Fraction.h"
#include <stdexcept>
namespace frac {
const std::string Fraction::doc = "Fraction类 v 0.01版.\n目前仅支持分数对象的构造、输出、加/减/乘/除运算.";
int Fraction::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 == 0 ? 1 : a;
}
Fraction::Fraction(int u, int d) : up(u), down(d) {
if (down == 0) throw std::invalid_argument("Fraction: 分母不能为0");
if (down < 0) {
up = -up;
down = -down;
}
int g = gcd(up, down);
up /= g;
down /= g;
}
int Fraction::get_up() const { return up; }
int Fraction::get_down() const { return down; }
void output(const Fraction& f) {
if (f.down == 1) {
std::cout << f.up;
} else {
std::cout << f.up << "/" << f.down;
}
}
Fraction operator+(const Fraction& f1, const Fraction& f2) {
return Fraction(f1.up * f2.down + f2.up * f1.down, f1.down * f2.down);
}
Fraction operator-(const Fraction& f1, const Fraction& f2) {
return Fraction(f1.up * f2.down - f2.up * f1.down, f1.down * f2.down);
}
Fraction operator*(const Fraction& f1, const Fraction& f2) {
return Fraction(f1.up * f2.up, f1.down * f2.down);
}
Fraction operator/(const Fraction& f1, const Fraction& f2) {
if (f2.up == 0) throw std::invalid_argument("Fraction: 分母不能为0");
return Fraction(f1.up * f2.down, f1.down * f2.up);
}
}
点击查看代码
#include <iostream>
#include <stdexcept>
#include "Fraction.h"
using namespace frac;
void test() {
std::cout << "测试1: Fraction类基础功能测试\n";
std::cout << "Fraction类测试:\n";
std::cout << Fraction::doc << "\n\n";
Fraction f1(5);
Fraction f2(-3, 4);
Fraction f3(f2);
Fraction f4 = f2 + f3;
Fraction f5 = f2 * f3 * -2;
std::cout << "f1 = "; output(f1); std::cout << "\n";
std::cout << "f2 = "; output(f2); std::cout << "\n";
std::cout << "f3 = "; output(f3); std::cout << "\n";
std::cout << "f4 = "; output(f4); std::cout << "\n";
std::cout << "f5 = "; output(f5); std::cout << "\n";
std::cout << "f5.get_up() = " << f5.get_up() << ", f5.get_down() = " << f5.get_down() << "\n";
std::cout << "f1 + f2 = "; output(f1 + f2); std::cout << "\n";
std::cout << "f1 - f2 = "; output(f1 - f2); std::cout << "\n";
std::cout << "f1 * f2 = "; output(f1 * f2); std::cout << "\n";
std::cout << "f1 / f2 = "; output(f1 / f2); std::cout << "\n";
std::cout << "f4 + f5 = "; output(f4 + f5); std::cout << "\n\n";
std::cout << "测试2: 分母为0测试:\n";
Fraction f6(42, 55);
Fraction f7(0);
std::cout << "f6 = "; output(f6); std::cout << "\n";
std::cout << "f7 = "; output(f7); std::cout << "\n";
std::cout << "f6 / f7 = ";
output(f6 / f7);
std::cout << "\n";
}
int main() {
try {
test();
} catch (const std::exception& e) {
std::cout << "terminate called after throwing an instance of 'std::invalid_argument'\n";
std::cout << " what(): " << e.what() << "\n";
}
return 0;
}
- 运行测试截图
![image]()
- 问题
我选择方案1分数类+友元函数。理由是在设计这个分数类时,加减乘除属于二目运算。如果采用方案2,为了不破坏类的封装性,就必须在类里写一堆公有的 get_up()、get_down() 等接口供外部调用,代码冗长可读性差。






浙公网安备 33010602011771号