实验2
实验任务一
源代码(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类对象数目
};
问题1
line1:创建对象,使用传入参数初始化成员;无传入参数时,默认 x=0、y=0。调用时机:直接定义对象、传入实参初始化对象,不是从已有同类对象拷贝或移动生成。
line2:以一个已存在的 T 对象为模板,新建对象,完成资源拷贝,两个对象相互独立。 调用时机:使用左值对象初始化新对象;函数按值传递对象、返回对象(无优化)时触发。
line3:接管传入对象的资源,不做深拷贝,效率更高;原对象失去原有资源。 调用时机:std::move 将左值转为右值,或者用临时对象初始化新对象。
line4:对象生命周期结束时,释放堆资源、清理对象。 调用时机:对象离开作用域、delete 释放动态对象时自动调用。
问题2:不能

错误1:get_cnt() 是普通成员函数,调用方式存在隐患 + 规范问题
错误2:计数错乱
问题3:
t1、t2、t3、t4 的作用域是 test 函数内部这一对大括号包裹的代码块,属于块作用域。它们的生命周期从变量定义语句执行、构造函数调用完成时开始,到代码块结束时,自动调用析构函数销毁,生命周期随之结束。 在这个作用域内,不能直接通过 t1 访问 m1、m2。m1、m2 是类的私有成员,私有成员仅能在类的成员函数、友元函数内部访问,外部代码无法直接访问。这体现了类的封装特性,将内部数据隐藏,对外只暴露规定的接口,实现信息隐藏。
问题4:报错,截图如下

功能:

会被销毁,因为C++ 栈展开机制,当异常抛出、退出当前代码块时,栈上已经构造完成的局部对象会自动调用析构函数释放资源,只有正在构造、还没有构造完成的对象不会调用析构函数。这里 t1、t2 构造已经完成,所以会正常销毁。
试验任务2:
源代码:
#ifndef COMPLEX_H
#define COMPLEX_H
#include <string>
class Complex
{
public:
static const std::string doc;
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);
friend bool is_not_equal(const Complex &c1, const Complex &c2);
private:
double rea;
double ima;
};
#endif
问题1:
①加const关键字,因为:const 对象只能调用const成员函数,编译器认为非 const 成员函数有可能修改对象内部数据,不允许在 const 对象上调用。如果不加:

②:不能
add成员函数的功能是修改对象内部的实部、虚部,它是会改变对象状态的非 const 成员函数。而 c6是 const 常量对象,初始化之后不允许修改内部数据,所以不能调用
const常量保护机制
问题2:
标准库模板类更加简洁。
自定义类依靠命名函数完成运算,标准库重载了运算符,可以直接使用 +、+=、==、!= 以及流输出 <<,书写简短,贴近数学表达。
二者存在内在关联,运算符本质上是特殊形式的函数,运算符表达式底层调用运算符重载函数,和自定义 add、is_equal 等普通函数实现的功能相同,仅语法形式有区别。
问题3:
①不是必须设为友元。可以做成普通非成员函数,借助类提供的公有接口获取实部和虚部,不需要直接访问私有成员 rea、ima,就能实现 output、abs、add 的全部功能。
②没有,如图:

③friend应谨慎使用,仅在少数合适场景启用。当函数或运算符重载需要同时访问多个不同类的私有成员,或者追求极高性能、不便新增公有接口时使用;优先依靠公有接口,尽量少用友元,避免破坏封装。
试验任务3:
补全后代码为:
#include "PlayerControl.h"
#include <algorithm>
#include <iostream>
int PlayerControl::total_cnt = 0;
PlayerControl::PlayerControl() {}
ControlType PlayerControl::parse(const std::string& control_str)
{
std::string s = control_str;
// 全部转小写
std::transform(s.begin(), s.end(), s.begin(),
[](unsigned char c) { return std::tolower(c); });
if (s == "play")
return ControlType::Play;
else if (s == "pause")
return ControlType::Pause;
else if (s == "next")
return ControlType::Next;
else if (s == "prev")
return ControlType::Prev;
else if (s == "stop")
return ControlType::Stop;
else
return ControlType::Unknown;
}
void PlayerControl::execute(ControlType cmd) const
{
++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;
}
运行截图:

问题:
const成员函数只禁止修改当前变量的普通成员变量;total_cnt是 static 静态成员,不属于单个对象,属于类,不受该 const 约束,可以修改。
试验任务4:
fraction.h源代码及运行截图:
#ifndef FRACTION_H
#define FRACTION_H
#include <string>
#include <stdexcept>
class Fraction
{
public:
static const std::string doc;
Fraction(int up0 = 0, int down0 = 1);
Fraction(const Fraction& other);
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);
private:
int up;
int down;
void reduce();
static int gcd(int a, int b);
};
#endif

fraction.cpp源代码:
#include "Fraction.h"
#include <iostream>
#include <algorithm>
const std::string Fraction::doc = R"(Fraction类 v 0.01版.
目前仅支持分数对象的构造、输出、加/减/乘/除运算.)";
int Fraction::gcd(int a, int b)
{
a = std::abs(a);
b = std::abs(b);
while (b != 0)
{
int r = a % b;
a = b;
b = r;
}
return a;
}
void Fraction::reduce()
{
if (down == 0)
throw std::invalid_argument("Fraction: 分母不能为0");
int g = gcd(up, down);
up /= g;
down /= g;
if (down < 0)
{
up = -up;
down = -down;
}
}
Fraction::Fraction(int up0, int down0) : up(up0), down(down0)
{
if (down0 == 0)
throw std::invalid_argument("Fraction: 分母不能为0");
reduce();
}
Fraction::Fraction(const Fraction& other)
{
up = other.up;
down = other.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)
{
if (f.down == 1)
std::cout << f.up;
else
std::cout << f.up << "/" << f.down;
}
Fraction add(const Fraction& a, const Fraction& b)
{
int new_up = a.up * b.down + b.up * a.down;
int new_down = a.down * b.down;
return Fraction(new_up, new_down);
}
Fraction sub(const Fraction& a, const Fraction& b)
{
int new_up = a.up * b.down - b.up * a.down;
int new_down = a.down * b.down;
return Fraction(new_up, new_down);
}
Fraction mul(const Fraction& a, const Fraction& b)
{
int new_up = a.up * b.up;
int new_down = a.down * b.down;
return Fraction(new_up, new_down);
}
Fraction div(const Fraction& a, const Fraction& b)
{
if (b.up == 0)
throw std::invalid_argument("Fraction: 分母不能为0");
int new_up = a.up * b.down;
int new_down = a.down * b.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();
}
回答问题:
我选择方案一。
理由:四则运算与输出函数需要直接访问分数私有成员分子、分母,友元可以直接访问私有数据,无需大量调用 get 接口;运算和分数类语义紧密绑定,可读性强;同时保持类内部数据封装,不会随意开放写权限。
实验总结:
本次实验练习 C++ 面向对象基础,掌握类与对象、各类构造析构函数、const\friend以及多文件代码组织。
类通过公私权限实现封装保护,私有成员外部不可直接访问,仅对外提供接口。const保护对象普通成员,但不限制属于类的静态成员。
普通成员归属于对象,静态成员为全类共享;静态数据需要类内声明、类外初始化。
不同构造函数用于对象初始化,析构在对象出作用域自动调用;抛出异常时栈上已创建对象会自动析构。
友元可访问私有成员,但会削弱封装,不可滥用,优先使用公有接口。
学会头文件放声明、源文件写实现的多文件开发模式,注意头文件防重复包含。
我体会到面向对象封装的设计思想,为后续学习打好基础。
浙公网安备 33010602011771号