实验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();
}
-
截图1-1
![1-1]()
-
回答问题
问题1: t.h中,T(int x = 0, int y = 0)是带有默认参数的普通构造函数,在创建新对象时被调用;T(const T &t)是复制构造函数,在用一个已存在对象去初始化新对象时被调用;T(T &&t)是移动构造函数,在用一个右值去初始化新对象时被调用;~T()是析构函数,在对象的生命周期结束时被调用。
t1触发了普通构造函数并使用默认参数;t2(3, 4)触发普通构造函数,传入参数;t3(t2)触发复制构造函数;t4(std::move(t2))触发移动构造函数。
问题2: 全部重新编译,得到报错信息“multiple definition of 'T::MAX_CNT'”。 即为不带const修饰的T::MAX_CNT被放在t.h中,同时被t.cpp和task1.cpp包含,被多重定义。
问题3: 对象 t1-t4 的作用域分别从定义点到最近的右侧花括号;生命期也是分别在定义点开始,但是在结束时,调用析构函数的顺序严格与构造顺序相反(t4->t3->t2->t1)。在这个作用域内不能通过 t1 访 问其私有成员 m1、m2,这体现了类的封装性。
问题4:头文件<stdexcept>包含了 C++ 标准库中预定义的异常类。throw 的核心作用是打断正常的程序执行流。
把t.cpp中T::MAX_CNT值改成2,重新编译运行,程序崩溃了。
截图1-2
![1-2]()
已经创建的对象不会被正常销毁,因为没有输出 "T destructor called.",说明析构函数未被调用。
实验任务2
- 源码
Complex.h
#pragma once
#include <string>
#include <iostream>
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 realpart;
double imagpart;
};
Complex.cpp
#include "Complex.h"
#include <cmath>
//类属性
const std::string Complex::doc = "a simplified complex class";
//构造函数
Complex::Complex(double r, double i) : realpart(r), imagpart(i){
}
//接口
double Complex::real() const{
return realpart;
}
double Complex::imag() const{
return imagpart;
}
void Complex::add(const Complex& c){
realpart+= c.realpart;
imagpart+= c.imagpart;
}
//友元函数
void output(const Complex& c){
if(c.imagpart >= 0)
std::cout<< c.realpart<< "+"<< c.imagpart<< "i";
if(c.imagpart < 0)
std::cout<< c.realpart<< "-"<< -c.imagpart<< "i";
}
double abs(const Complex& c){
return std::sqrt(c.realpart*c.realpart + c.imagpart*c.imagpart);
}
Complex add(const Complex& c1, const Complex& c2){
Complex ans;
ans.realpart=c1.realpart+c2.realpart;
ans.imagpart=c1.imagpart+c2.imagpart;
return ans;
}
bool is_equal(const Complex& c1, const Complex& c2){
return (c1.realpart==c2.realpart)&&(c1.imagpart==c2.imagpart);
}
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();
}
-
截图2-1
![2-1]()
-
回答问题
问题1:在测试代码中,c6是const对象。
① 在设计 Complex 类的成员函数时,必须在成员函数的声明和定义的末尾加上const;若不加,会报关于this的限定符丢失错误。
② 作为const对象,c6在初始化后不允许再被修改。在测试代码中添加执行c6.add(c2);编译不能通过;编译时就会报错因为函数试图修改const对象;这体现了C++取最保守权限以保证数据安全的机制。
问题2: 标准库模板类 complex 的用法更简洁;据此推断运算的内在底层就是函数,从而实现例如int/double不同类型数据的运算重载。
问题3:
① 设为友元不是必须的;可以通过real()/imag()函数来获取实部和虚部数据。
② 标准库 std::complex 未把 abs 设为友元。
截图2-2
![2-2]()
https://www.cppreference.com/cpp/numeric/complex
③ 首先,为了保证封装性,在工业场景中避免使用友元。其次,有三种场景友元难以被替代:1,使用std::cout << c;这种写法打印对象的私有数据时;2,运算左右操作数类型不同需要隐式类型转换时;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>
#include <cctype>
int PlayerControl::total_cnt = 0;
PlayerControl::PlayerControl() {}
char tolower_func(unsigned char c) {
return std::tolower(c);
}
ControlType PlayerControl::parse(const std::string& control_str) {
std::string lower_str = control_str;
std::transform(lower_str.begin(), lower_str.end(), lower_str.begin(), tolower_func);
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();
}
-
截图3-1
![3-1]()
-
问题回答
void execute(ControlType cmd) const;是const成员函数,但是total_cnt被声明为static int total_cnt,属于全局变量而不属于特定对象,所以允许代码++total_cnt。
实验任务4
- 源码
Fraction.h
#pragma once
#include <string>
#include <iostream>
class Fraction {
public:
//类属性
static const std::string doc;
//构造函数
Fraction(int up0= 0, int down0= 1);
//接口
int get_up() const;
int get_down() const;
Fraction negative() const;
private:
//对象属性
int up;
int down;
//辅助函数
void normalize();
};
//自由函数
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 <stdexcept>
#include <cmath>
//gcd
int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
//类属性
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");
}
if (down < 0) {
up= -up;
down= -down;
}
normalize();
}
//辅助函数
void Fraction::normalize() {
if (up == 0) {
down = 1;
return;
}
int divisor = gcd(std::abs(up), std::abs(down));
up /= divisor;
down /= divisor;
}
//接口
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) {
if (f.get_down() == 1)
std::cout << f.get_up();
else
std::cout << f.get_up() << "/" << f.get_down();
}
Fraction add(const Fraction& f1, const Fraction& f2) {
int new_up= f1.get_up() * f2.get_down() + f2.get_up() * f1.get_down();
int new_down= f1.get_down() * f2.get_down();
return Fraction(new_up, new_down);
}
Fraction sub(const Fraction& f1, const Fraction& f2) {
int new_up= f1.get_up() * f2.get_down() - f2.get_up() * f1.get_down();
int new_down= f1.get_down() * f2.get_down();
return Fraction(new_up, new_down);
}
Fraction mul(const Fraction& f1, const Fraction& f2) {
int new_up= f1.get_up() * f2.get_up();
int new_down= f1.get_down() * f2.get_down();
return Fraction(new_up, new_down);
}
Fraction div(const Fraction& f1, const Fraction& f2) {
int new_up= f1.get_up() * f2.get_down();
int new_down= f1.get_down() * f2.get_up();
return Fraction(new_up, new_down);
}
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();
}
-
截图4-1
![4-1]()
-
我选择了方案2,分数类 + 命名空间自由函数。原因是经过task2后我认识到友元是会破坏代码封装性的;而且先前课上提到过命名空间自由函数的延展性更好,便于后期添加功能。
实验总结
收获:task1中,如果没有 try-catch 捕获,出现异常程序崩溃后已经创建的对象不会被正常销毁。而task4中,分母为 0 时抛出 std::invalid_argument 异常。体现出在工业级设计中,构造函数抛出异常是安全的,但析构函数抛出异常会导致资源泄漏或程序直接崩溃,应当准备具异常捕获的程序终止代码。






浙公网安备 33010602011771号