实验2 现代C++编程初体验
实验任务一
源代码
T.h
点击查看代码
#pragma once
#include <string>
// 类T: 声明
class T {
// 对象属性、方法
public:
T(int x = 0, int y = 0); // 普通构造函数
T(const T &t); // 复制构造函数
T(T &&t); // 移动构造函数
~T(); // 析构函数
void adjust(int ratio); // 按系数成倍调整数据
void display() const; // 以(m1, m2)形式显示T类对象信息
private:
int m1, m2;
// 类属性、方法
public:
static int get_cnt(); // 显示当前T类对象总数
public:
static const std::string doc; // 类T的描述信息
static const int max_cnt; // 类T对象上限
private:
static int cnt; // 当前T类对象数目
// 类T友元函数声明
friend void func();
};
// 普通函数声明
void func();
T.cpp
点击查看代码
#include "T.h"
#include <iostream>
#include <string>
// 类T实现
// static成员数据类外初始化
const std::string T::doc{"a simple class sample"};
const int T::max_cnt = 999;
int T::cnt = 0;
// 类方法
// 对象方法
T::T(int x, int y): m1{x}, m2{y} {
++cnt;
std::cout << "T constructor called.\n";
}
T::T(const T &t): m1{t.m1}, m2{t.m2} {
++cnt;
std::cout << "T copy constructor called.\n";
}
T::T(T &&t): m1{t.m1}, m2{t.m2} {
++cnt;
std::cout << "T move constructor called.\n";
}
T::~T() {
--cnt;
std::cout << "T destructor called.\n";
}
void T::adjust(int ratio) {
m1 *= ratio;
m2 *= ratio;
}
void T::display() const {
std::cout << "(" << m1 << ", " << m2 << ")" ;
}
// 普通函数实现
void func() {
T t5(42);
t5.m2 = 2049;
std::cout << "t5 = "; t5.display(); std::cout << '\n';
}
int T::get_cnt() {
return cnt;
}
task1.cpp
点击查看代码
#include "T.h"
#include <iostream>
void test_T();
int main() {
std::cout << "test Class T: \n";
test_T();
std::cout << "\ntest friend func: \n";
func();
}
void test_T() {
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 = "; t1.display(); cout << endl;
T t2(3, 4);
cout << "t2 = "; t2.display(); cout << endl;
T t3(t2);
t3.adjust(2);
cout << "t3 = "; t3.display(); cout << endl;
T t4(std::move(t2));
cout << "t4 = "; t4.display(); cout << endl;
cout << "test: T objects'current count: " << T::get_cnt() << endl;
}
运行结果

问题1:
去掉line36,不能运行

根据图片可知编译器找不到fun(),因为类T内部的friend void func()仅声明其为友元,但不会自动在全局作用域中声明func(),导致编译器在调用func()时无法识别该标识符。
问题2:
第九行:普通构造函数
功能:用来初始化T的对象,为成员变量m1,m2赋初始值。
调用时机:在创建类T的对象时。
第十行:复制构造函数
功能:用一个已存在的T类对象,复制其成员变量值来初始化新的T类对象。
调用时机:用一个对象初始化另一个对象时。
第十一行:移动构造函数
功能:利用临时对象(右值)的资源来初始化新对象,避免不必要的拷贝开销。
调用时机:用右值初始化对象的时候。
第十二行:析构函数
功能:在对象生命周期结束时,执行资源清理操作。
调用时机:在对象生命周期结束时。
问题3:
T.cpp中,line8-10,剪切到T.h的末尾,不能编译运行。

原因是,把静态成员的“定义”(带初始化)从 T.cpp 剪到 T.h 后,T.h 被 T.cpp 与 task1.cpp 同时包含,两个目标文件各自生成一份定义。
doc 是非整型静态对象,必须且只能在一个翻译单元定义一次。cnt 是非常量静态,同样只能定义一次。max_cnt 虽是 const int,但当前写法需要一个唯一的定义;把定义放进头文件会在每个包含它的 .cpp 里各生成一份。
实验任务二
源代码
Complex.h
点击查看代码
#pragma once
#include <string>
class Complex {
private:
double real; // 实部
double imag; // 虚部
public:
// 静态成员:类说明文档
static const std::string doc;
// 构造函数
Complex(); // 无参构造(0+0i)
Complex(double r); // 单参构造(实部r,虚部0)
Complex(double r, double i); // 双参构造(实部r,虚部i)
Complex(const Complex& other); // 拷贝构造
// 成员函数:获取实部和虚部(const成员,支持const对象调用)
double get_real() const;
double get_imag() const;
// 成员函数:当前复数 += 另一个复数
void add(const Complex& other);
// 友元函数声明
friend void output(const Complex& c); // 输出复数
friend double abs(const Complex& c); // 计算模
friend Complex add(const Complex& a, const Complex& b); // 两复数相加(返回新对象)
friend bool is_equal(const Complex& a, const Complex& b); // 判断相等
friend bool is_not_equal(const Complex& a, const Complex& b); // 判断不等
};
Complex.cpp
点击查看代码
#include "Complex.h"
#include <iostream>
#include <cmath>
// 静态成员初始化
const std::string Complex::doc = "a simplified Complex class";
// 构造函数实现
Complex::Complex() : real(0.0), imag(0.0) {}
Complex::Complex(double r) : real(r), imag(0.0) {}
Complex::Complex(double r, double i) : real(r), imag(i) {}
Complex::Complex(const Complex& other) : real(other.real), imag(other.imag) {}
// 成员函数实现
double Complex::get_real() const {
return real;
double Complex::get_imag() const {
return imag;
}
void Complex::add(const Complex& other) {
real += other.real;
imag += other.imag;
}
// 友元函数实现
void output(const Complex& c) {
if (c.imag >= 0) {
std::cout << c.real << "+" << c.imag << "i";
}
else {
std::cout << c.real << c.imag << "i";
}
}
double abs(const Complex& c) {
return std::sqrt(c.real * c.real + c.imag * c.imag);
}
Complex add(const Complex& a, const Complex& b) {
return Complex(a.real + b.real, a.imag + b.imag);
}
bool is_equal(const Complex& a, const Complex& b) {
return (a.real == b.real) && (a.imag == b.imag);
}
bool is_not_equal(const Complex& a, const Complex& b) {
return !is_equal(a, b);
}
task2
点击查看代码
#include "Complex.h"
#include <iostream>
#include <iomanip>
#include <complex>
#include "../../../C语言代码/实验二.2/Complex.h"
void test_Complex();
void test_std_complex();
int main() {
std::cout << "*******测试1: 自定义类Complex*******\n";
test_Complex();
std::cout << "\n*******测试2: 标准库模板类complex*******\n";
test_std_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);
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.real = " << c5.get_real()
<< ", c5.imag = " << c5.get_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;
}
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;
const std::complex<double> c5(3.5);
cout << "c1 = " << c1 << endl;
cout << "c2 = " << c2 << endl;
cout << "c3 = " << c3 << endl;
cout << "c4 = " << c4 << endl;
cout << "c5.real = " << c5.real()
<< ", c5.imag = " << c5.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;
}
运行结果

问题1:
(1)在使用形式上,我觉得标准库更加简洁一些。
标准库内置所有复数核心运算符重载(+、-、*、/、==、!=等),直接按数学逻辑使用,无需手动实现,而自定义类Complex若需支持多种数值类型,需要手动实现模板或者多个重载类,较为繁琐。
(2)函数和运算两者,都是基于数学的定义,对于复数进行运算,内在运算规则相同。
设计的目的都是为了封装负数的数据,避免直接操作导致一些不必要的错误。
问题2:
(1)否。自定义Complex中, output/abs/add/ 等均设为友元,它们不是必须访问私有数据才能实现其功能。可以通过共有访问器get_real和get_imag来访问私有数据。
(2)标准库 std::complex 没有把 abs 设为友元。
该函数通过 std::complex
调用 z.real() 获取实部(返回 T 类型);
调用 z.imag() 获取虚部(返回 T 类型);
(3)使用友元
a.想要输出类的私有成员可以设为友元,但不是必须。
b.当外部函数功能实现需要依赖私有成员时,需要设为友元。
问题3:
将 Complex 类的拷贝构造函数声明为 explicit。例如:explicit Complex(const Complex& other),其中explicit 关键字的作用是禁止构造函数被隐式调用,仅允许显式调用(如直接初始化 Complex c3(c2);)。
实验任务三
源代码
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 <iostream>
#include <algorithm>
int PlayerControl::total_cnt = 0;
PlayerControl::PlayerControl() {}
ControlType PlayerControl::parse(const std::string& control_str) {
//将大写字母转换为小写字母以实现不区分大小写的比较
std::string lower_str = control_str;
for (size_t i = 0; i < lower_str.size(); ++i) {
if (lower_str[i] >= 'A' && lower_str[i] <= 'Z') {
lower_str[i] = lower_str[i] + ('a' - 'A');
}
}
ControlType type = ControlType::Unknown;
if (lower_str == "play") type = ControlType::Play;
else if (lower_str == "pause") type = ControlType::Pause;
else if (lower_str == "next") type = ControlType::Next;
else if (lower_str == "prev") type = ControlType::Prev;
else if (lower_str == "stop") type = ControlType::Stop;
++total_cnt;
return type;
};
void PlayerControl::execute(ControlType cmd) const {
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 "PlayerControl.h"
#include <iostream>
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();
}
运行结果

实验任务四
源代码
Fraction.h
点击查看代码
#pragma once
#include <string>
namespace fraction {
class Fraction {
public:
static std::string doc();
Fraction(int a = 0, int b = 1);
Fraction(const Fraction& other);
int get_up() const;
int get_down() const;
Fraction negative() const;
private:
void simplify();
int up, down;
};
// 工具函数声明
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 <iostream>
#include <cstdlib>
#include "Fraction.h"
namespace fraction {
// 接口实现
std::string Fraction::doc() {
return "Fraction类 v0.01版.\n目前仅支持分数对象的构造、输出、加/减/乘/除运算.";
}
Fraction::Fraction(int a, int b) : up(a), down(b) {
simplify();
}
Fraction::Fraction(const Fraction& other) : up(other.get_up()), down(other.get_down()) {
}
static int gcd(int a, int b) {
a = std::abs(a);
b = std::abs(b);
while (b != 0) {
int temp = a % b;
a = b;
b = temp;
}
return a;
}
void Fraction::simplify() {
if (down == 0) {
return;
}
int gcd_val = gcd(std::abs(up), std::abs(down));
if (gcd_val != 0) {
up /= gcd_val;
down /= gcd_val;
}
if (down < 0) {
up *= -1;
down *= -1;
}
}
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) {
const int u = f.get_up();
const int d = f.get_down();
if (d == 0) {
std::cout << "分母不能为0";
} else if (d == 1) {
std::cout << u;
} else {
std::cout << u << "/" << d;
}
}
Fraction add(const Fraction& f1, const Fraction& f2) {
const int u = f1.get_up() * f2.get_down() + f2.get_up() * f1.get_down();
const int d = f1.get_down() * f2.get_down();
return Fraction(u, d);
}
Fraction sub(const Fraction& f1, const Fraction& f2) {
const int u = f1.get_up() * f2.get_down() - f2.get_up() * f1.get_down();
const int d = f1.get_down() * f2.get_down();
return Fraction(u, d);
}
Fraction mul(const Fraction& f1, const Fraction& f2) {
const int u = f1.get_up() * f2.get_up();
const int d = f1.get_down() * f2.get_down();
return Fraction(u, d);
}
Fraction div(const Fraction& f1, const Fraction& f2) {
const int u = f1.get_up() * f2.get_down();
const int d = f1.get_down() * f2.get_up();
return Fraction(u, d);
}
}
task4
点击查看代码
#include "Fraction.h"
#include <iostream>
void test1();
void test2();
int main() {
std::cout << "测试1: Fraction类基础功能测试\n";
test1();
std::cout << "\n测试2: 分母为0测试: \n";
test2();
}
void test1() {
using std::cout;
using std::endl;
cout << "Fraction类测试: " << endl;
cout << fraction::Fraction::doc() << endl << endl;
fraction::Fraction f1(5);
fraction::Fraction f2(3, -4), f3(-18, 12);
fraction::Fraction f4(f3);
cout << "f1 = "; fraction::output(f1); cout << endl;
cout << "f2 = "; fraction::output(f2); cout << endl;
cout << "f3 = "; fraction::output(f3); cout << endl;
cout << "f4 = "; fraction::output(f4); cout << endl;
const fraction::Fraction f5(f4.negative());
cout << "f5 = "; fraction::output(f5); cout << endl;
cout << "f5.get_up() = " << f5.get_up()
<< ", f5.get_down() = " << f5.get_down() << endl;
cout << "f1 + f2 = "; fraction::output(fraction::add(f1, f2)); cout << endl;
cout << "f1 - f2 = "; fraction::output(fraction::sub(f1, f2)); cout << endl;
cout << "f1 * f2 = "; fraction::output(fraction::mul(f1, f2)); cout << endl;
cout << "f1 / f2 = "; fraction::output(fraction::div(f1, f2)); cout << endl;
cout << "f4 + f5 = "; fraction::output(fraction::add(f4, f5)); cout << endl;
}
void test2() {
using std::cout;
using std::endl;
fraction::Fraction f6(42, 55), f7(0, 3);
cout << "f6 = "; fraction::output(f6); cout << endl;
cout << "f7 = "; fraction::output(f7); cout << endl;
cout << "f6 / f7 = "; fraction::output(fraction::div(f6, f7)); cout << endl;
}

问题
我的选择:命名空间 + 自由函数。
(1)友元函数实现可直接访问私有成员,写法简洁,编译期内联优化空间大。但是破坏封装、增加耦合与重编译成本;一旦内部表示变化,友元实现易受影响。
(2)类+static方案二元运算的对称性差(调用写成Fraction::add(a,b)或a.add(b),左边受限)。
(3)自由函数的方案对称性更好:二元运算不偏向任一操作数,支持两边隐式转换。但是在使用工具函数的时候可发现性差,用户不容易发现名字。而且可能出现命名冲突。
综上,我选择了命名空间 + 自由函数,保证封装性,工具函数放入fraction避免与全局add/sub/...冲突。

浙公网安备 33010602011771号