OOP 实验2_类和对象_基础编程1
类和对象_基础编程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 cout:" << T::MAX_CNT << endl;
cout << "T objects'current cout:" << 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.h中,line6-9给出了各种构造函数、析构函数。用文字简洁说明它们各自的功能、调用时机。结合t1-t4,说明它们分别触发了哪个构造函数。
![image]()
T(int x = 0, int y = 0)普通构造函数:用给定值初始化新对象的数据成员m1、m2,可以是无参数,有一个参数或两个参数。调用时机是用初始值创建新对象时。
T(const T &t)复制构造函数:用已经存在的同类型对象初始化新对象。调用时机是用已存在的左值对象初始化新对象时。
T(T &&t)移动构造函数:用右值(临时对象)初始化新对象。调用时机是用右值初始化新对象时。
~T()析构函数:对象销毁前释放内存。调用时机是对象生命期结束时系统自动调用。
t1()调用的是普通构造函数,使用了默认参数x=0,y=0
t2(3,4)调用的是普通构造函数,使用给定实参x=3,y=4
t3(t2)调用的是复制构造函数,t2是左值
t4(std::move(t2))调用的是移动构造函数,std::move(t2)把t2转换成右值 -
问题2:t.cpp中,line7-9,剪切到t.h的末尾,重新编译,程序能否正确编译。如不能,以截图形式给出报错信息,分析原因。
![image]()
程序不能正确编译,报错信息如下:
![image]()
原因是多重定义了变量。在t.h(头文件)中直接定义变量或常量,并且这个头文件被task1.cpp和t.cpp都包含,编译时会在执行task1.cpp时创建MAX_CNT变量,在执行t.cpp时创建MAX_CNT变量,最后拼接时发现有两个叫MAX_CNT的变量,于是导致报错:多重定义。 -
问题3:类T的测试模块test 中,说明对象 t1-t4 的作用域和生命期。并思考:在这个作用域内,能否通过 t1 访问其私有成员 m1、m2?这体现了类的什么特性?
t1-t4都是test()函数中内层花括号{}块内的局部对象。它们的作用域从各自的定义点开始,到内层块结束为止;生命期与作用域一致,进入定义点时创建(调用对应的构造函数),离开块时销毁(按定义逆序调用析构函数)。
在这个作用域内不能通过t1访问其私有成员m1、m2,私有成员只有类内函数和友元函数可以访问。这体现了类的封装特性,通过访问权限控制(public和private),把数据的实现封装在类内部,只暴露必要的公有接口。 -
问题4.1:t.cpp中包含了头文件
#include<stdexcept>,构造函数中均使用了以下代码。使用搜索引擎/AI查询throw 功能。
![image]()
throw用于抛出异常:当执行到throw时,它会立即中断当前函数的正常执行流程,携带一个异常对象沿函数调用链向外逐层寻找匹配的catch处理块;若一直找不到匹配的catch,程序将调用std::terminate异常终止。简单说,throw是“扔出问题”,catch时“接住问题”,如果throw抛出的异常一直没人catch,程序就会终止。 -
问题4.2:把t.cpp中
T::MAX_CNT值改成2,重新编译、运行程序。观察输出,程序是正常结束还是崩溃了?给出截图运行结果。
如果崩溃了,已经创建的对象(如t1),会被正常销毁吗?给出答案,并说明理由。
T::MAX_CNT值改成2,重新编译、运行程序,程序崩溃了,运行结果如图。已经创建的对象(t1、t2)不能被正常销毁,因为T::MAX_CNT值改成2后,只能创建2个对象,创建t3时,检查当前创建对象数量等于最大创建对象数量,执行throw抛出异常,终止执行后续代码,所以析构函数不能正常执行,t1、t2不能被正常销毁。
![image]()
任务2
源代码
Comples.h
#pragma once
#include <string>
class Complex{
public:
Complex(double r = 0, double i = 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); //判断复数是否相等 相等true,否则false
friend bool is_not_equal(const Complex &c1, const Complex &c2); //判断复数是否相等 不相等true,否则false
static const std::string doc; // 类的描述信息
private:
double real_, imag_;
};
Comples.cpp
#include "Complex.h"
#include <iostream>
#include <cmath>
// static 成员数据:类内声明、类外初始化
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 || c.imag_ == 0)
std::cout << c.real_ << " + " << c.imag_ << "i";
else
std::cout << c.real_ << " - " << std::fabs(c.imag_) << "i";
}
double abs(const Complex &c){
return sqrt(c.real_ * c.real_ + c.imag_ * c.imag_);
}
Complex add(const Complex &c1, const Complex &c2){
Complex c_new;
c_new.real_ = c1.real_ + c2.real_;
c_new.imag_ = c1.imag_ + c2.imag_;
return c_new;
}
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 !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();
}
运行测试截图


问题回答
-
问题1:在测试代码中,c6是const对象。
① 为了让c6.real()和c6.imag()能编译通过,在设计 Complex 类的成员函数时,必须加上什么关键字?如果不加,编译器会报什么错?(请简述或截图报错信息)。
在设计成员函数时,必须加const关键字,如果不加,编译器报错信息如下图。
VScode问题提示:
![image]()
编译报错信息:
![image]()
原因是const对象调用了非const成员函数,在C++实现中const对象只能调用const成员函数,非const对象既可以调用非const成员函数,也可以调用const成员函数。
② 作为const对象,c6在初始化后不允许再被修改。在测试代码中添加执行c6.add(c2),能编译通过吗?为什么?这体现了类的什么保护机制?
不能编译通过,因为c6是const对象,初始化之后不允许修改,add()是非const成员函数,执行c6.add(c2)等于c6=c6+c2,会修改c6,与const约束冲突。这体现了类的const保护机制。 -
问题2:比较自定义类
Complex和标准库模板类Complex的用法,在使用形式上,哪种更简洁?据此推断函数和运算是否存在内在关联呢?
标准库模版类Complex更简洁,加法直接写c2 + c3,比较直接写c1 == c2,输出直接写cout << c2;而自定义类要写成add(c2, c3)、is_equal(c1, c2)、output(c2)这样的函数调用形式。说明运算符本质上是函数,执行c2 + c3其实就是对operator+(c2, c3)这个函数的调用。 -
问题3:
① 本练习中,output、abs、add(非成员版本)等被设为Complex的友元。这是必须的吗?如果将其声明为普通非成员函数(不用friend),能否实现相同的功能?简述思路。
不是必须的。这些函数要访问实部、虚部可以通过成员函数real()、imag()获得,所以将其声明为普通非成员函数可以实现相同的功能。
② 标准库std::complex是否把abs设为友元?(查阅 cppreference后回答,并提供页面具体链接地址)
链接地址:https://en.cppreference.com/cpp/numeric/complex/abs
![image]()
标准库没有把abs设为友元,是一个普通的非成员函数。
③ 工业场景中,什么时候才考虑使用friend?和AI讨论后,简洁概括你的思考和结论。(限150字内)
工业代码中,只有当某个外部函数/类确实需要访问私有成员,并且通过公有接口实现会明显变差时,才考虑用friend,并且友元之间最好属于同一个抽象。如果只是为了省事,并且有可以使用的公有接口,不建议用友元,破坏数据的封装。
任务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() {}
ControlType PlayerControl::parse(const std::string &control_str) {
if (control_str == "play") return ControlType::Play;
else if (control_str == "pause") return ControlType::Pause;
else if (control_str == "next") return ControlType::Next;
else if (control_str == "prev") return ControlType::Prev;
else if (control_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 <algorithm>
#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) {
std::string s{control_str};
std::transform(s.begin(), s.end(), s.begin(), static_cast<int(*)(int)>(std::tolower));
if(s == "quit")
break;
ControlType cmd = controller.parse(s);
controller.execute(cmd);
std::cout << "Current Player control: " << PlayerControl::get_cnt() << "\n\n";
}
}
int main() {
test();
}
运行测试截图

问题回答
- 接口
void execute(ControlType cmd) const;是const成员函数,为什么在其内部实现允许代码++total_cnt?
因为total_cnt是static数据成员,是静态成员变量,属于类的成员,由类的所有对象共享但不属于任何一个对象。而const成员函数的语义是不修改对象的非静态数据成员,因此++total_cnt不违反const语义,编译器允许。说明const保护的是对象级状态,类级共享状态(static成员)不受const成员函数约束。
问题发现

这是我最开始写的代码,但在执行后发现存在一个问题:当输入QUIT时,程序并没有进行大小写转换成quit终止程序,而是执行else return ControlType::Unknown;语句,并计数,运行截图如下图:

排查发现是task3.cpp里的循环语句顺序的问题。
输入 QUIT 时:程序进入循环,拿到字符串 control_str(此时它的值是 QUIT),第一步执行if(control_str == "quit")。因为字符串比较区分大小写,QUIT 不等于 quit,所以没有 break,程序没有退出。接着往下走,调用controller.parse("QUIT")成功地把 QUIT 转换成了小写的 quit,但因为parse函数里只匹配了play/pause/next/prev/stop,所以最终返回了 ControlType::Unknown。接着执行execute(ControlType::Unknown),于是打印了[Error] unknown control并且把总计数total_cnt加到了 7。最后,手动输入了 quit,程序才真正退出。

于是我修改了task3.cpp里的循环语句顺序如下:

发现此时parse函数中就不用再进行大小写转换,修改如下图,并得到对应运行测试截图如上图。

任务4
源代码
Fraction.h
#pragma once
#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; // 求负运算
static const std::string doc;
private:
int up, down;
void simplify(); // 内部工具函数:约分
};
namespace frac{
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<iostream>
#include<numeric>
#include<cmath>
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();
}
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 Fraction::simplify(){
if (down == 0)
throw std::invalid_argument("Fraction: 分母不能为0");
if (up == 0){
down = 1;
return;
}
int common = std::gcd(up, down);
up /= common;
down /= common;
if (down < 0){
up = -up;
down = -down;
}
}
//命名空间自由函数
namespace frac{
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){
if (f2.get_up() == 0)
throw std::invalid_argument("Fraction: 分母不能为0");
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 = "; frac::output(f1); cout << endl;
cout << "f2 = "; frac::output(f2); cout << endl;
cout << "f3 = "; frac::output(f3); cout << endl;
cout << "f4 = "; frac::output(f4); cout << endl;
const Fraction f5(f4.negative());
cout << "f5 = "; frac::output(f5); cout << endl;
cout << "f5.get_up() = " << f5.get_up()
<< ", f5.get_down() = " << f5.get_down() << endl;
cout << "f1 + f2 = "; frac::output(frac::add(f1, f2)); cout << endl;
cout << "f1 - f2 = "; frac::output(frac::sub(f1, f2)); cout << endl;
cout << "f1 * f2 = "; frac::output(frac::mul(f1, f2)); cout << endl;
cout << "f1 / f2 = "; frac::output(frac::div(f1, f2)); cout << endl;
cout << "f4 + f5 = "; frac::output(frac::add(f4, f5)); cout << endl;
}
void test2() {
using std::cout;
using std::endl;
Fraction f6(42, 55), f7(0, 3);
cout << "f6 = "; frac::output(f6); cout << endl;
cout << "f7 = "; frac::output(f7); cout << endl;
cout << "f6 / f7 = "; frac::output(frac::div(f6, f7)); cout << endl;
}
int main() {
std::cout << "测试1: Fraction类基础功能测试\n";
test1();
std::cout << "\n测试2: 分母为0测试: \n";
test2();
}
运行结果截图

问题回答
- 分数运算
(output/add/sub/mul/div ),你选择的是哪种设计方案?你的决策理由?
方案1:分数类 + 友元函数
方案2:分数类 + 命名空间自由函数
我选择的是方案2:分数类 + 命名空间自由函数,正如任务2问题3所讨论的,工业代码中,只有当某个外部函数/类确实需要访问私有成员,并且通过公有接口实现会明显变差时,才考虑用friend。如果只是为了省事,并且有可以使用的公有接口,不建议用友元,破坏数据的封装。
并且命名空间自由函数不依赖于类的内部实现细节,如果未来类的内部表示发生变化,只需调整自由函数的实现,而无需修改类的友元声明,灵活性更高。
但是ai建议我这道题用方案1,因为在一个独立、结构清晰的 Fraction 类设计中,“高内聚”(方案1)远比“绝对隔离”(方案2)更重要。,不过我想再练习一下命名空间自由函数,所以还是选择方案2。








浙公网安备 33010602011771号