实验2
1.实验任务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 coutn:" << 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 object'current count:" << T::get_cnt() << endl;
}
int main() {
std::cout << "test Class T:\n";
test();
}
运行截图

问题1
·T(int x=0,int y=0):普通构造函数,在对象被创建时利用特定的值构造对象,将对象初始化为一个特定的状态,构造函数在对象别创建的时候(eg.T t1和T t2(3,4))将被自动调用
·T(const T &t):复制构造函数,其作用是使用一个已经存在的对象(由复制构造函数的参数指定),去初始化同类的一个新对象,调用有3种情况:
(1)用类的一个对象去初始化该类的另一个对象时
(2)函数的形参为类的对象,调用函数时
(3)函数的返回值是类的对象,返回函数值时
·T(T &&t):移动构造函数,通过移动而不复制实参的高性能方式构建新对象,移动构造函数的参数为该类对象的右值引用,在构造中移动源对象资源,构造后源对象不再指向被移动的资源,源对象可重新赋值或者被销毁,在发生移动语义的时候调用,如T t4(std::move(t2))
·~T():析构函数,用来完成对象被删除前的一些清理工作,析构函数是在对象的生存期即将结束的时刻被自动调用的
· t1,t2触发普通构造函数,t3触发复制构造函数,t4触发移动构造函数;t1-t4都会各触发一次析构函数
问题2
不能,截图信息如下:

类的静态数据成员(如static const std::string doc)属于类本身,如果在头文件中直接初始化,当多个源文件包含该头文件时,会导致重复定义,正确的做法是在t.h中声明,在t.cpp中定义和初始化
问题3
由于t1-t4定义在一对大括号{}内,所以它们的作用域在该大括号内部,生命周期从定义开始,到大括号结束。不能通过t1访问其私有成员,封装特性,封装使一部分成员充当类与外部的接口,而将其他的成员隐蔽起来,private成员m1,m2是本类的私有数据,外部无法直接访问
问题4
·当程序执行到throw语句时,他会创建一个异常对象(由后面的表达式产生)并立刻跳出当前函数,沿着函数调用栈向上寻找能够处理该异常的 catch 块。如果没有找到匹配的 catch,程序会调std::terminate 导致程序异常终止(通常表现为程序崩溃)。
·eg.所给例子里面假设调用时写了T t2(3,100)导致throw执行的话,那么t2不会被成功创建,throw后面的代码全部停止执行,程序会拿着 "T:maximum object count exceeded" 这个信息,去寻找哪里的代码写了 try ... catch ... 来接住这个错误。如果整段代码都没人接,程序就会直接崩溃(闪退)。
·程序崩溃了,截图如下
会被正常销毁,当 throw 语句被执行时,函数会立刻停止执行后续代码,开始向外层调用者抛出异常并寻找catch块。在这个过程中,C++保证:在异常抛出之前,作用域内已经构造成功的局部对象,其析构函数一定会被自动调用。
2.实验任务2
源代码
Complex.cpp
#include"Complex.h"
#include<iostream>
#include<cmath>
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) {
if (c.imag_ < 0) {
std::cout << c.real_ << "-" << -c.imag_ << "i";
}
else {
std::cout << c.real_ << "+" << c.imag_ << "i";
}
}
bool is_equal(const Complex& c1, const Complex& c2) {
if ((c1.real_ == c2.real_) && (c1.imag_ == c2.imag_))
return true;
return false;
}
bool is_not_equal(const Complex& c1, const Complex& c2) {
if ((c1.real_ == c2.real_) && (c1.imag_ == c2.imag_))
return false;
return true;
}
Complex add(const Complex& c1, const Complex& c2) {
return Complex(c1.real_ + c2.real_, c1.imag_ + c2.imag_);
}
double abs(const Complex& c) {
return sqrt(c.real_ * c.real_ + c.imag_ * c.imag_);
}
Complex.h
#pragma once
#include<string>
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 bool is_equal(const Complex& c1, const Complex& c2);
friend bool is_not_equal(const Complex& c1, const Complex& c2);
friend Complex add(const Complex& c1, const Complex& c2);
friend double abs(const Complex& c);
private:
double real_;
double imag_;
};
运行截图

问题1
(1)必须加上const关键字,如果没加,会产生这种错误:
(2)不能,c6是一个只读对象,而void add(const Complex &c)并没有被const修饰,不能允许const对象调用非const成员函数,ai告诉我这是const常对象保护机制
问题2
标准库模板类complex更简洁,具有内在关联,调用的函数add,is_equal等抽象成了+和=这种运算符,即运算符本质上就是函数,我认为是抽象出了这种函数的本质思想,精简为运算符的功能来实现
问题3
(1)不是必须的。两种方法各有取舍,设为友元可以避免给每一个外部函数都提供公共接口,暴露给每个人,但是会增加接触到私有数据的机会
(2)不是友元,链接https://zh.cppreference.com/w/cpp/numeric/complex/abs
(3)当外部函数必须访问类的私有/受保护成员,且无法通过公有接口高效实现时,才考虑使用友元。例如紧密协作的类:两个类需要互相访问内部实现,但又不适合合并或使用继承时。ai还告诉我有重载流操作符跟堆成的二元运算符,但是我不太理解
3.实验任务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) {
// xxx
std::string lower_str = control_str;
std::transform(lower_str.begin(), lower_str.end(), lower_str.begin(),
[](unsigned char c) {return std::tolower(c);});
if (lower_str == "play") return ControlType::Play;
else if (lower_str == "pause") return ControlType::Pause;
else if (lower_str == "next") return ControlType::Next;
else if (lower_str == "prev") return ControlType::Prev;
else if (lower_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;
}
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();
}
运行截图

问题
void execute(ControlTyoe cmd) const;相当于是在说这个函数不会修改该对象的非静态成员变量,this指针类型是const PlayerControl*,它是隐含于每一个类的非静态成员函数中的特殊指针,而total_cnt是static int静态成员变量,对类的静态成员的访问是不依赖于对象的,它属于整个类,不属于任何一个具体的对象实例。因此可以。
实验任务4
源代码
Fraction.h
#pragma once
#include<string>
class Fraction {
public:
Fraction(int up0, int down0=1);
Fraction(const Fraction& f);
~Fraction();
int get_up() const;
int get_down() const;
Fraction negative();
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);
static const std::string doc;
private:
int up, down;
};
Fraction.cpp
#include"Fraction.h"
#include<iostream>
#include<cmath>
#include<stdexcept>
#include<numeric>
const std::string Fraction::doc{"Fraction类v 0.01版\n目前仅支持分数对象的构造,输出,加/减/乘/除运算."};
static int gcd(int a,int b) {
while(b!=0) {
int temp=b;
b=a%b;
a=temp;
}
return std::abs(a);
}
static void simplify(int &up,int &down) {
if(down<0) {
up=-up;
down=-down;
}
if (up == 0) {
down = 1;
return;
}
int g=gcd(up,down);
up/=g;
down/=g;
}
Fraction::Fraction(int up0,int down0):up{up0},down{down0} {
if(down==0)
throw std::invalid_argument("Fraction:分母不能为0");
simplify(up, down);
}
Fraction::Fraction(const Fraction &f):up{f.up},down{f.down} {
}
Fraction::~Fraction() {
}
int Fraction::get_up() const {
return up;
}
int Fraction::get_down() const {
return down;
}
Fraction Fraction::negative() {
Fraction t(*this);
t.up=-t.up;
return t;
}
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) {
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) {
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"
void test1() {
using std::cout;
using std::endl;
cout << "Fraaction类测试: " << 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是因为我看前面的其他task中有使用友元函数的,所以想要照着例子再练一练这种书写的方式,但是我写完代码看到问题之后其实觉得方案二更好一点,friend实际上破坏了类的封装性,而分数类+命名空间自由函数则可以保证这种性质,如果不想反复修改类头文件,方案二也是更好的选择
实验总结
最后一个实验其实我的并没输出出来案例里的最后一行,程序直接终止了,询问ai搞了半天也没有成功。在写最后一个代码的时候一开始的版本没有注意到书写格式的要求,即当分母是负数的时候,要记得把负号转移给分子,因为我们输出的时候一般是-3/4而不是3/-4,同时Fraction::Fraction(int up0,int down0):up{up0},down{down0}实现的时候也忘了要化简,调用simplify()函数。整体各个task在自己编写的时候感觉挺不熟练或者说卡壳的需要反复去查看之前给的例子来书写。
浙公网安备 33010602011771号