实验2 类和对象_基础编程1
任务1
一、源代码
//t.cpp
#include "t.hpp"
#include <iostream>
#include <stdexcept>
#include <string>
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 << ")";
}
//t.hpp
#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();
friend void output(const T &t);
static const std::string doc;
static const int MAX_CNT;
private:
int m1,m2;
static int current_cnt;
};
//task1.cpp
#include <iostream>
#include <utility>
#include "t.hpp"
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):初始化新对象;创建新对象且提供参数(或无参)时。
(2)复制构造T(const T &t):初始化新对象;当用已存在的对象通过拷贝的方式进行初始化时调用。
(3)移动构造T(T &&t):初始化新对象;当用右值通过转移的方式进行初始化时调用。
(4)析构函数~T():销毁对象,释放内存;当对象的生命周期结束、delete、程序结束时。 -
t1~t4 所调用的函数
(1)T t1:默认构造
(2)T t2(3, 4):普通构造
(3)t3(t2):复制构造
(4)t4(std::move(t2)):移动构造
问题二:
可以。
问题三:
- 作用域:整个
test()内。 - 生命期:函数内层
{}内。 - 能否通过 t1 访问私有成员 m1、m2 ?:不能。因为
test()是外部函数。 - 类的特性:封装。
问题四:
- throw 的功能是什么?:
throw用于抛出异常。当程序遇到无法处理的错误时(如本题中对象数量超过MAX_CNT),通过throw抛出一个异常对象,会立刻中断当前正常的程序执行流。 - 把
MAX_CNT改成 2 后,程序运行结果如何?:崩溃了
![image]()
- t1会被正常销毁吗?:会。AI给的理由是这涉及 C++ 的 栈展开(Stack Unwinding) 机制。当 throw 抛出异常时,程序会沿着函数调用栈向上寻找 catch 块。在退栈的过程中,系统会保证所有已经成功构造的局部对象(如 t1、t2)的析构函数被自动调用。这是 C++ 异常安全机制的一部分,确保即使程序遇到异常崩溃,已经分配的内存资源也能被正确回收,防止内存泄漏。
任务2
一、源代码
//task2
#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();
}
//Complex.h
#pragma once
#include <cmath>
#include <string>
using namespace std;
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(Complex c);
friend void output(const Complex& c);
friend double abs(const Complex& c);
friend Complex add(Complex c1,Complex c2);
friend bool is_equal(Complex c1,Complex c2);
friend bool is_not_equal(Complex c1,Complex c2);
private:
double real_;
double imag_;
};
//Complex.cpp
#include <iomanip>
#include <iostream>
#include "Complex.h"
using namespace std;
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_}{}
void Complex::add(Complex c){
real_+=c.real_;
imag_+=c.imag_;
}
double Complex::real() const{
return real_;
}
double Complex::imag() const{
return imag_;
}
void output(const Complex& c){
cout << c.real_ << "+" << c.imag_ << "i\n";
}
double abs(const Complex& c){
return sqrt(c.real_*c.real_+c.imag_*c.imag_);
}
Complex add(Complex c1,Complex c2){
Complex c3;
c3.real_ = c1.real_ + c2.real_;
c3.imag_ = c1.imag_ + c2.imag_;
return c3;
}
bool is_equal(Complex c1,Complex c2){
if(c1.real_==c2.real_&& c1.imag_ == c2.imag_) return true;
return false;
}
bool is_not_equal(Complex c1,Complex c2){
return (!is_equal(c1,c2));
}
二、运行结果截图

三、回答问题
问题一:
①加const。const对象不能调用非const函数,编译器会报错:passing 'const Complex' as 'this' argument discards qualifiers
②不能。因为 c6 是 const 对象,而 add 是会修改对象。体现了类的 const 保护机制,保证了 const 的对象在初始化后不能被修改。
问题二:
标准库更简洁。C++ 中的运算符(如 +、=/=、<< 等)本质上就是函数的一种“缩写”,是因为它内部进行了重载,给这些运算符赋予了类似于函数的功能。
问题三:
①不是必须的。如果不用 friend,可以通过调用类的公有接口( real() 和 imag())来获取数据
②没有将 abs 设为友元。https://en.cppreference.com/w/cpp/numeric/complex/abs
③一般在以下情况使用 friend:(1) 运算符重载(如 <<、>>)需要访问类的私有数据;(2) 两个类需要紧密协作、且一个类需要访问另一个类的内部数据时;(3) 需要提高性能,绕过公有接口直接操作私有数据时。但应优先使用公有接口,避免破坏封装性。总结:慎重使用,优先考虑公有接口。
任务3
一、源代码
//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();
}
//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;//不能是空的
std::transform(control_str.begin(), control_str.end(),str.begin(),[](unsigned char c){return tolower(c);});//不能直接传给tolower
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;
}
二、运行结果截图

三、回答问题
问题一:
因为 total_cnt 是 static(静态)成员变量 。const成员函数只是不能修改非静态成员。从this指针的角度来看,const让this指向常量,不能修改对象的成员,但因为 total_cnt 是 static 变量,它根本不在对象 a 里面,所以不是通过this指针去修改的。
任务4
一、源代码
//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();
}
//Fraction.h
#pragma once
#include <string>
class Fraction {
public:
//类属性
static const std::string doc;
//构造函数
Fraction(int up = 0, int down = 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& 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);
//化简
void simplify();
private:
int up;
int down;
};
//Fraction.cpp
#include "Fraction.h"
#include <iostream>
#include <stdexcept>
#include <cmath>
using namespace std;
//类属性
const string Fraction::doc = "Fraction类 v 0.01版.\n目前仅支持分数对象的构造、输出、加/减/乘/除运算.";
//构造函数
Fraction::Fraction(int up0, int down0) : up(up0), down(down0) {
if (down == 0) {
throw invalid_argument("Fraction: 分母不能为0");
}
simplify(); //构造时立刻化简
}
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);
}
//工友元工具函数
//PS:用引用传效率更高,后同
void output(const Fraction& f) {
//如果分母为1,直接输出分子
if (f.down == 1) {
cout << f.up;
} else {
cout << f.up << "/" << f.down;
}
}
//加 (a/b + c/d = (ad+bc)/bd)
Fraction add(const Fraction& f1, const Fraction& f2) {
return Fraction(f1.up * f2.down + f2.up * f1.down, f1.down * f2.down);
}
//减 (a/b - c/d = (ad-bc)/bd)
Fraction sub(const Fraction& f1, const Fraction& f2) {
return Fraction(f1.up * f2.down - f2.up * f1.down, f1.down * f2.down);
}
//乘 (a/b * c/d = ac/bd)
Fraction mul(const Fraction& f1, const Fraction& f2) {
return Fraction(f1.up * f2.up, f1.down * f2.down);
}
//除 (a/b / c/d = ad/bc)
Fraction div(const Fraction& f1, const Fraction& f2) {
if (f2.up == 0) {//因为 b和 d既然构造出来就肯定不会是 0了 ,所以只需检查 c
throw std::invalid_argument("Fraction: 分母不能为0");
}
return Fraction(f1.up * f2.down, f1.down * f2.up);
}
//递归
int gcd(int a, int b) {
if(b == 0) return a;
else return gcd(b, a%b);
}
//化简分数、处理符号
void Fraction::simplify() {
if(up == 0) {
down = 1;//因为当分母为 1时,会直接输出分子
return;
}
//符号都放在分子上
if(down < 0) {
up = -up;
down = -down;
}
int g = gcd(abs(up), abs(down));//求最大公因子
up /= g;
down /= g;
}
二、运行结果截图

三、回答问题
问题一:
方案一。
- 可以直接访问私有数据,更加便捷高效,无需额外编写
get_up()和get_down()来获取数据 - 相比于为了自由函数而把
up和down改成公有(public),友元函数在提供操作便利的同时,依然保持了类的良好封装性。(虽然可能带来一定的风险) - 题目提供的测试代码
task4.cpp中,运算符的调用形式是add(f1, f2)以及output(f1)。使用友元方案可以完美适配这种调用方式,不需要像方案2那样去修改测试代码加上frac::前缀。


浙公网安备 33010602011771号