实验2
实验任务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); // 友元函数
static const std::string doc; // 类描述信息
static const int MAX_CNT; // 对象数量上限
private:
int m1, m2; // 对象数据成员
static int current_cnt; // 当前对象数目
};
t.cpp
点击查看代码
#include "t.h"
#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 << ")";
}
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
普通构造函数:用传入的 int 值初始化对象的 m1、m2,校验对象数量并计数自增。调用时机:以整数参数创建新对象时,如t1、t2。
复制构造函数:用已有对象拷贝初始化新对象,保留原对象数据并计数自增。调用时机:用已有对象直接初始化新对象时,如t3。
移动构造函数:转移右值对象的数据初始化新对象,减少拷贝开销,计数自增。调用时机:用std::move转为右值初始化对象时,如t4。
对应触发:t1→普通构造;t2→普通构造;t3→复制构造;t4→移动构造。
2

不能正确编译。原因:静态成员必须遵循「类内声明、类外定义」规则。若将初始化代码放入头文件,头文件被多个源文件包含时会触发多重定义错误,违反 C++ 单一定义规则(ODR),链接阶段报multiple definition错误。
3
t1-t4 的作用域是test函数内花括号形成的块作用域,生命期从定义行开始,到块结束时终止。
不能通过t1直接访问私有成员m1、m2。这体现了类的封装特性:通过 private 权限隐藏内部数据,仅允许通过公有接口交互,保障数据安全与类的内聚性。
4

实验任务2
源代码
complex.h
点击查看代码
#pragma once
#include <string>
class Complex {
public:
static const std::string doc;
Complex(double real = 0, double imag = 0);
Complex(const Complex& other);
double real() const;
double 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);
private:
double real_;
double imag_;
};
complex.cpp
点击查看代码
#include "Complex.h"
#include <iostream>
#include <cmath>
const std::string Complex::doc = "a simplified complex class";
Complex::Complex(double real, double imag) : real_(real), imag_(imag) {}
Complex::Complex(const Complex& other) : real_(other.real_), imag_(other.imag_) {}
double Complex::real() const {
return real_;
}
double Complex::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.cpp
点击查看代码
#include <iomanip>
#include <iostream>
#include <complex>
#include "Complex.h"
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;
}
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
① 必须给real()和imag()加上const关键字,声明为 const 成员函数。不加会编译报错:passing 'const Complex' as 'this' argument discards qualifiers,即 const 对象无法调用非 const 成员函数。
② 不能编译通过。add()是非 const 成员函数,会修改对象自身,而 const 对象禁止被修改。这体现了类的const 数据保护机制,通过限定对象不可变,保障状态安全。
2
标准库std::complex用法更简洁。
二者本质一致:运算符是特殊的函数。
3
① 不是必须的。不用 friend 也可实现:通过类的公有接口real()、imag()获取数据,在普通函数中完成计算与输出。
③ AI讨论如下;工业场景仅在非成员函数必须频繁访问私有成员、公有接口无法高效实现,或运算符重载需要语法便利性时使用 friend。friend 会削弱封装,应优先用公有接口,尽量少用。
实验任务3
源代码
playcontrol.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);
void execute(ControlType cmd) const;
static int get_cnt();
private:
static int total_cnt;
};
playcontrol.cpp
点击查看代码
#include "PlayerControl.h"
#include <algorithm>
#include <iostream>
#include <cctype>
int PlayerControl::total_cnt = 0;
PlayerControl::PlayerControl() {}
ControlType PlayerControl::parse(const std::string& control_str) {
std::string lower_str;
lower_str.reserve(control_str.size());
for (char c : control_str) {
lower_str += static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
}
if (lower_str == "play") return ControlType::Play;
if (lower_str == "pause") return ControlType::Pause;
if (lower_str == "next") return ControlType::Next;
if (lower_str == "prev") return ControlType::Prev;
if (lower_str == "stop") return ControlType::Stop;
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;
}
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();
}
运行结果截图

问题回答
1
total_cnt是静态成员变量,属于整个类而非单个对象,存储在全局数据区。const 成员函数的const仅限定this指向的对象本身不可修改,保证不改变对象的非静态成员状态;静态成员不属于对象状态,因此在 const 成员函数中可以修改
实验任务4
源代码
Fraction.h
点击查看代码
#pragma once
#include <string>
class Fraction {
public:
static const std::string doc;
Fraction(int up = 0, int down = 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_;
static int gcd(int a, int b);
void normalize(); // 约分并规范符号(分母恒正)
};
Fraction.cpp
点击查看代码
#include "Fraction.h"
#include <iostream>
#include <stdexcept>
#include <cstdlib>
const std::string Fraction::doc = "Fraction类 v 0.01版.\n目前仅支持分数对象的构造、输出、加/减/乘/除运算.";
int Fraction::gcd(int a, int b) {
a = std::abs(a);
b = std::abs(b);
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
void Fraction::normalize() {
if (down_ == 0) {
throw std::invalid_argument("Fraction: 分母不能为0");
}
// 统一符号:分母恒正,符号放分子
if (down_ < 0) {
up_ = -up_;
down_ = -down_;
}
int g = gcd(up_, down_);
up_ /= g;
down_ /= g;
}
Fraction::Fraction(int up, int down) : up_(up), down_(down) {
normalize();
}
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 up = a.up_ * b.down_ + b.up_ * a.down_;
int down = a.down_ * b.down_;
return Fraction(up, down);
}
Fraction sub(const Fraction& a, const Fraction& b) {
int up = a.up_ * b.down_ - b.up_ * a.down_;
int down = a.down_ * b.down_;
return Fraction(up, down);
}
Fraction mul(const Fraction& a, const Fraction& b) {
int up = a.up_ * b.up_;
int down = a.down_ * b.down_;
return Fraction(up, down);
}
Fraction div(const Fraction& a, const Fraction& b) {
if (b.up_ == 0) {
throw std::invalid_argument("Fraction: 分母不能为0");
}
int up = a.up_ * b.down_;
int down = a.down_ * b.up_;
return Fraction(up, 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();
}
运行结果截图

问题回答
1
方案 1:分数类 + 友元函数
决策理由:
- 完全兼容题目提供的测试代码,无需修改调用方式。
- 运算函数与类功能高度耦合,友元形式在语义和代码组织上更紧凑内聚。

浙公网安备 33010602011771号