实验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:T(int x=0, int y=0)是普通构造函数,功能是初始化对象的数据成员,可以无参(此时为默认参数),也可以带参数创建对象。在创建对象时调用。
T(const T &t)是拷贝构造函数,功能是用已有对象初始化新对象,T t3(t2);中t2是已有对象,用它初始化了新对象t3。在使用已有对象初始化新对象时调用。
T(T &&t)是移动构造函数,功能是使用右值初始化新对象。在使用std::move()等产生右值的表达式初始化时调用,T t4(std::move(t2));这里就是把t2强制转换成了右值,被t4接管。
~T()是析构函数,功能是对象销毁时执行清理工作,在对象生命周期结束时调用。
问题2:我贴过去之后编译成功了,但是作为static静态成员数据,放到头文件,会导致多重定义,理论上会出错,然后我去问ai说是因为只有 task1.cpp 包含 t.h,所以这三行定义只会在 task1.cpp 出现一次,链接器只看到一份符号,就不会报多重定义,编译就成功....我有点没搞懂这个,是我编译有问题吗,因为问了两个ai给我的回答不同。
问题3:作用域是从各自声明的位置开始,到内部花括号结束,生命期是从对象构造完成开始,也是到内部花括号结束时销毁。销毁顺序是t4,t3,t2,t1。因为m1,m2是私有成员private中定义的,所以不能通过t1直接访问,这体现了类的封装性和数据隐藏机制,外部只能通过公有接口访问数据。
问题4:throw用于抛出异常。当程序遇到不允许继续执行的情况时,可以通过throw把异常交给异常处理机制。
任务2
Complex.h源码
#pragma once
#include <string>
class Complex {
public:
Complex(double real = 0.0, double imag = 0.0);
Complex(const Complex& c) = default;
double real() const;
double imag() const;
void add(const Complex& c);
static const std::string doc;
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_;
};
Complex.cpp源码
#include "Complex.h"
#include <iostream>
#include <cmath>
const std::string Complex::doc =
"a simplified complex class";
Complex::Complex(double real, double imag)
: real_{real}, imag_{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 << " - " << -c.imag_ << "i";
}
else {
std::cout << " + " << c.imag_ << "i";
}
}
double abs(const Complex& c) {
return std::hypot(c.real_, 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);
}
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.1:必须加上const,如果不加,编译器会认为成员函数可修改,而c6是const函数,不能调用没有const限定的普通函数成员。
1.2:不能,因为add会修改对象的实部和虚部,而c6作为const对象,不能被修改,这体现了const对象保护机制。
问题2:标准库类模板更简洁,原因是标准库使用了运算符重载。
函数和运算符之间存在联系:运算符重载本质上也是通过函数实现的,可以让对象像内置数据类型一样使用 +、==、+= 等运算符。
问题3:不是必须的。
如果将它们设计成普通非成员函数,也可以实现相同功能。
实现方法:通过类提供的公有接口 real() 和 imag() 获取实部、虚部,再通过公有构造函数创建新的复数对象,这样不需要friend,也可以实现。
任务3
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;
};
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 cmd=control_str;
std::transform(
cmd.begin(),cmd.end(),cmd.begin(),[](unsigned char c){
return static_cast<char>(std::tolower(c));
}
);
if(cmd=="play"){
return ControlType::Play;
}
else if(cmd=="pause"){
return ControlType::Pause;
}
else if(cmd=="next"){
return ControlType::Next;
}
else if(cmd=="prev"){
return ControlType::Prev;
}
else if(cmd=="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;
}
task3.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 cmd=control_str;
std::transform(
cmd.begin(),cmd.end(),cmd.begin(),[](unsigned char c){
return static_cast<char>(std::tolower(c));
}
);
if(cmd=="play"){
return ControlType::Play;
}
else if(cmd=="pause"){
return ControlType::Pause;
}
else if(cmd=="next"){
return ControlType::Next;
}
else if(cmd=="prev"){
return ControlType::Prev;
}
else if(cmd=="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;
}
运行截图

回答问题
因为total_cnt是静态成员变量,const成员函数限制的是当前对象的普通非静态成员数据,不能通过该函数修改当前对象的普通数据成员。而 static 成员变量属于整个类,被所有对象共享,不属于某个具体对象。
任务4
Fraction.h源代码
#pragma once
#include <string>
class Fraction{
public:
Fraction(int up0=0,int down0=1);
Fraction(const Fraction& f) = default;
int get_up() const;
int get_down() const;
Fraction negative() const;
static const std::string doc;
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 normalize();
};
Fraction.cpp源代码
#include "Fraction.h"
#include <iostream>
#include <stdexcept>
#include <limits>
//求最大公约数,用于约分
namespace {
long long gcd_ll(long long a, long long b) {
if (a < 0)
a = -a;
if (b < 0)
b = -b;
while (b != 0) {
long long temp = a % b;
a = b;
b = temp;
}
return a == 0 ? 1 : a;
}
//检查并创建约分后的函数
Fraction make_fraction(long long n, long long d) {
if (d == 0) {
throw std::invalid_argument(
"Fraction: 分母不能为0"
);
}
if (d < 0) {
n = -n;
d = -d;
}
long long g = gcd_ll(n, d);
n /= g;
d /= g;
if (n < std::numeric_limits<int>::min()
|| n > std::numeric_limits<int>::max()
|| d > std::numeric_limits<int>::max()) {
throw std::overflow_error(
"Fraction: 计算结果超出int范围"
);
}
return Fraction(
static_cast<int>(n),
static_cast<int>(d)
);
}
}
const std::string Fraction::doc =
"Fraction类 v 0.01版.\n"
"目前仅支持分数对象的构造、输出、加/减/乘/除运算.";
Fraction::Fraction(int up0, int down0)
: up{up0}, down{down0} {
normalize();
}
void Fraction::normalize() {
if (down == 0) {
throw std::invalid_argument(
"Fraction: 分母不能为0"
);
}
long long n = up;
long long d = down;
if (d < 0) {
n = -n;
d = -d;
}
long long g = gcd_ll(n, d);
n /= g;
d /= g;
if (n < std::numeric_limits<int>::min()
|| n > std::numeric_limits<int>::max()
|| d > std::numeric_limits<int>::max()) {
throw std::overflow_error(
"Fraction: 结果超出int范围"
);
}
up = static_cast<int>(n);
down = static_cast<int>(d);
}
int Fraction::get_up() const {
return up;
}
int Fraction::get_down() const {
return down;
}
Fraction Fraction::negative() const {
if (up == std::numeric_limits<int>::min()) {
throw std::overflow_error(
"Fraction: 求负时超出int范围"
);
}
return Fraction(-up, down);
}
void output(const Fraction& f) {
std::cout << f.up << "/" << f.down;
}
Fraction add(
const Fraction& f1,
const Fraction& f2
) {
long long n =
static_cast<long long>(f1.up) * f2.down
+ static_cast<long long>(f2.up) * f1.down;
long long d =
static_cast<long long>(f1.down) * f2.down;
return make_fraction(n, d);
}
Fraction sub(
const Fraction& f1,
const Fraction& f2
) {
long long n =
static_cast<long long>(f1.up) * f2.down
- static_cast<long long>(f2.up) * f1.down;
long long d =
static_cast<long long>(f1.down) * f2.down;
return make_fraction(n, d);
}
Fraction mul(
const Fraction& f1,
const Fraction& f2
) {
long long n =
static_cast<long long>(f1.up) * f2.up;
long long d =
static_cast<long long>(f1.down) * f2.down;
return make_fraction(n, d);
}
Fraction div(
const Fraction& f1,
const Fraction& f2
) {
if (f2.up == 0) {
throw std::invalid_argument(
"Fraction: 不能除以0"
);
}
long long n =
static_cast<long long>(f1.up) * f2.down;
long long d =
static_cast<long long>(f1.down) * f2.up;
return make_fraction(n, d);
}
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,分数类与友元函数相结合的设计方式。因为分数的加减乘除运算需要访问两个分数对象的私有分子和分母,使用友元函数可以直接访问私有成员,减少额外接口的设计,使代码更加简洁。同时,友元函数属于非成员函数,能够体现对象之间的独立运算关系。另外也是受任务2影响对友元更熟悉,过多使用会降低封装性,这个需要注意。

浙公网安备 33010602011771号