实验2
任务1
1.实验源码
#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类对象数目
};
// 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 << ")";
}
#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 :普通构造函数是初始化时通过括号内值定义对象,没有初值时自动赋值(0,0) 。复制构造函数是初始化时赋值可以用已经定义过的对象来赋值。移动构造函数可以直接接管已经存在的同类型对象的资源。析构函数用于销毁对象,避免资源占用。
t1触发了普通构造函数,t2 触发了普通构造函数 ,t3触发了复制构造函数,t4触发了移动构造函数。
问题2:

结果如图可以正常运行。
问题3:作用域是从各自的构造完成开始到line29的内层' } '结束,生命周期是从定义构造完成开始到line29处' } '自动调用析构函数结束。t1不能访问私密成员,体现了类的封装性。
问题4: throw用于抛出异常,程序沿调用链向上寻找匹配的 catch 处理块;找不到则终止程序。

不会正常销毁,因为T destructor called没有输出可以看出来。
任务2
1.源代码
#pragma once
#include <iostream>
#include <string>
class Complex {
public:
Complex(double r = 0.0, double i = 0.0);
Complex(const Complex &c);
Complex(Complex &&c);
Complex &operator=(const Complex &c) = default;
Complex &operator=(Complex &&c) = default;
~Complex();
double real() const;
double imag() const;
void add(const Complex &c);
friend void output(const Complex &c);
friend double abs(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);
static const std::string doc;
private:
double a;
double b;
};
#include "Complex.h"
#include <cmath>
#include <iostream>
#include <string>
const std::string Complex::doc = "a simplified complex class";
Complex::Complex(double r, double i) : a{r}, b{i} {
}
Complex::Complex(const Complex &c) : a{c.a}, b{c.b} {
}
Complex::Complex(Complex &&c) : a{c.a}, b{c.b} {
}
Complex::~Complex() {
}
double Complex::real() const {
return a;
}
double Complex::imag() const {
return b;
}
void Complex::add(const Complex &c) {
a += c.a;
b += c.b;
}
void output(const Complex &c) {
std::cout << c.a;
if (c.b >= 0) {
std::cout << " + " << c.b << 'i';
} else {
std::cout << " - " << -c.b << 'i';
}
}
double abs(const Complex &c) {
return std::sqrt(c.a * c.a + c.b * c.b);
}
bool is_equal(const Complex &c1, const Complex &c2) {
return c1.a == c2.a && c1.b == c2.b;
}
bool is_not_equal(const Complex &c1, const Complex &c2) {
return !is_equal(c1, c2);
}
Complex add(const Complex &c1, const Complex &c2) {
return Complex(c1.a + c2.a, c1.b + c2.b);
}
#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关键字,不加编译器会报如下错误

表示把const成员对象传给非const成员函数。
(2)不能编译通过,add()函数会修改数据,const对象不能调用它,体现了类的const保护机制。
二.
标准库更简洁 , 运算可能本身就是一种函数,运算符只是便于理解,本质还是靠函数实现功能。
三.
不一定要定义为友元函数,其目的只是访问类中的private接口,但是存在real()和image()这两个公有接口,通过它们俩也可以获得数据。
任务3
1.源代码
#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) {
std::string s = control_str;
for (char& ch : s) {
if (ch >= 'A' && ch <= 'Z')
ch = ch + ('a' - 'A');
}
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;
}
#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.问题探究
1.const成员函数约束的是不能修改当前对象的数据成员,以及不能调用非const成员函数,total_cnt是共享静态成员不在const保护范围内。
任务4
1.源代码
#pragma once
#include <iostream>
#include <string>
class Fraction {
public:
Fraction(int up0, int down0 = 1);
Fraction(const Fraction &f);
int get_up() const;
int get_down() const;
Fraction negative() const;
friend void output(const Fraction &f);
friend Fraction add(const Fraction &a, const Fraction &b);
friend Fraction sub(const Fraction &a, const Fraction &b);
friend Fraction mul(const Fraction &a, const Fraction &b);
friend Fraction div(const Fraction &a, const Fraction &b);
static const std::string doc;
private:
int up;
int down;
void normalize();
static int gcd(int a, int b);
};
#include "Fraction.h"
#include <iostream>
#include <stdexcept>
#include <string>
const std::string Fraction::doc =
"Fraction类 v 0.01版.\n目前仅支持分数对象的构造、输出、加/减/乘/除运算.";
int Fraction::gcd(int a, int b) {
if (a < 0) a = -a;
if (b < 0) b = -b;
while (b != 0) {
int t = a % b;
a = b;
b = t;
}
return a;
}
void Fraction::normalize() {
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;
}
Fraction::Fraction(int up0, int down0) : up{up0}, down{down0} {
normalize();
}
Fraction::Fraction(const Fraction &f) : up{f.up}, down{f.down} {
}
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 &a, const Fraction &b) {
return Fraction(a.up * b.down + b.up * a.down, a.down * b.down);
}
Fraction sub(const Fraction &a, const Fraction &b) {
return Fraction(a.up * b.down - b.up * a.down, a.down * b.down);
}
Fraction mul(const Fraction &a, const Fraction &b) {
return Fraction(a.up * b.up, a.down * b.down);
}
Fraction div(const Fraction &a, const Fraction &b) {
return Fraction(a.up * b.down, a.down * b.up);
}
#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.问题探究
方案1 ,(1)用友元函数可以直接访问类的私有成员,不用依赖公用接口。(2)task4中调用形式就是以非成员函数形式的,所以次啊用友元函数形式。(3)友元函数权限覆盖更少,对数据保护性更好,更可以体现类的封装性。

浙公网安备 33010602011771号