实验2
实验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 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();
}
2.运行截图

3.问题回答
-
问题1:普通构造函数在创建新对象时调用,这里带有默认参数,允许创建对象时不给参数,可以为创建的新对象初始化,t1、t2调用的都是普通构造函数,t2自己带参数;复制构造函数使用一个已经存在的同类对象去初始化一个新对象,传参传的是左值,t3调用的就是复制构造函数;移动构造函数也是利用已存在的同类对象初始化新对象,但传参传的是右值,t4调用的就是移动构造函数;析构函数在对象生命期结束之后释放内存。
-
问题2:报错:报错信息:multiple definition of `T::MAX_CNT'和multiple definition of'T::current_cnt' task1.cpp里面包含了t.h,t.cpp里也包含了t.h,展开后这些变量被定义了两次,,所以有多重定义的报错,静态成员变量不能放在.h头文件里
![task1-2]()
-
问题3:t1、t2、t3、t4的生命期是从他们被定义的那一行开始到这一整个代码块的}结束,即line28的};不能,m1,m2是私有成员,t1在外部函数test()里面,无法访问m1,m2,体现了类的封装性。
-
问题4:查阅资料知:throw是c++中用于抛出异常的关键字,当程序遇到无法正常处理的情况时,会抛出一个异常对象,比如这里就是抛出了std::runtime_error类型的对象,并带有一条字符串作为错误提示;崩溃了,运行截图如下。已经创建的对象会被正常销毁,查询资料知,c++异常处理机制保证了栈展开,当异常被抛出时,程序会沿着调用栈退出,退出时自动调用已经成功构造的对象的析构函数。

任务2
1.源代码
Complex.h
点击查看代码
#pragma once
#include<string>
class Complex{
public:
const static 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_,imag_;
};
Complex.cpp
点击查看代码
#include <iostream>
#include <cmath>
#include "Complex.h"
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 << " + " << c.imag_ << "i";
else
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 (c1.real_!=c2.real_ || c1.imag_!=c2.imag_);
}
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();
}
2.运行截图

3.问题回答
- 问题1:必须加上const,不加的话会报错,报错信息如下

c6作为const对象,初始化之后不允许被修改。add()只是普通函数,c6不能调用,所以添加c6.add(c2)不能通过,体现了类的常量正确性保护机制。
- 问题2:对比标准库中的模板类可知,标准库的使用更加简洁,他并没有add()之类的需要自己写的函数,直接用运算类模板,符合阅读习惯。同时也说明c++中的运算符其实就是函数的实现。
- 问题3:不是必须的,如果声明为普通函数的话,在Complex类的public里面添加成员函数,然后把这些函数声明在private里面,就可以通过public里的成员函数去读取。
我通过查阅https://en.cppreference.com/cpp/numeric/complex/abs 看到,标准库std::complex没有把abs设为友元,就是一个普通的函数模板。
查阅ai后,我了解到工业场景中只有必须访问私有成员,但无法通过公有成员去访问时才会使用friend。比如在一些紧密配合的类型,如容器和迭代器,迭代器需要访问容器内部的节点,但节点结构属于容器的实现细节,可以把权限授予对应的迭代器。friend毕竟破坏了封装性。
任务3
1.源代码
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 str=control_str;
int i;
for(i=0;i<str.length();i++)
{
unsigned char c=str[i];
str[i]=std::tolower(c);
}
if(str=="play")
return ControlType::Play;
if(str=="pause")
return ControlType::Pause;
if(str=="next")
return ControlType::Next;
if(str=="prev")
return ControlType::Prev;
if(str=="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;
}
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();
}
2.运行截图

3.问题回答
- 因为total_cnt被声明为static变量,它不属于某个类的特定对象,而是属于整个类,所以不受const控制,可以修改。
任务4
1.源代码
Fraction.h
点击查看代码
#pragma once
#include <iostream>
#include <string>
class Fraction{
public:
static const std::string doc;
Fraction(int up0=0,int down0=1);
Fraction(const Fraction &f)=default;
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();
static int gcd(int a,int b);
};
void output(const Fraction &f);
Fraction add(const Fraction &f1,const Fraction &f2);
Fraction sub(const Fraction &f1,const Fraction &f2);
Fraction mul(const Fraction &f1,const Fraction &f2);
Fraction div(const Fraction &f1,const Fraction &f2);
Fraction.cpp
点击查看代码
#include "Fraction.h"
#include <cmath>
#include <stdexcept>
const std::string Fraction::doc="Fraction类 v 0.01版.\n""目前仅支持分数对象的构造、输出、加/减/乘/除运算.";
Fraction::Fraction(int up0,int down0):up{up0},down{down0}{
if(down==0)
throw std::invalid_argument("Fraction:分母不能为0");
simplify();
}
int Fraction::get_up() const{
return up;
}
int Fraction::get_down() const{
return down;
}
Fraction Fraction::negative() const{
return Fraction(-up,down);
}
int Fraction::gcd(int a,int b){
a=std::abs(a);
b=std::abs(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 gcd=Fraction::gcd(up,down);
up/=gcd;
down/=gcd;
}
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){
return Fraction(f1.up*f2.down+f2.up*f1.down,f1.down*f2.down);
}
Fraction sub(const Fraction &f1,const Fraction &f2){
return Fraction(f1.up*f2.down-f2.up*f1.down,f1.down*f2.down);
}
Fraction mul(const Fraction &f1,const Fraction &f2){
return Fraction(f1.up*f2.up,f1.down*f2.down);
}
Fraction div(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);
}
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();
}
2.运行截图

3.问题回答
- 我选择的是分数类+友元函数。选择理由一个是感觉友元函数访问私有成员up和down方便一些,再一个就是确实对友元函数的使用更熟悉一些。


浙公网安备 33010602011771号