实验2
task1:
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 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:
普通构造函数:
新建对象的时候给里面的 m1、m2 赋初始值,同时统计当前对象数量 + 1。 什么时候调用:直接写 T t1;、T t2(3,4); 这种新建对象的代码,就会触发它。
复制构造函数:
拿一个已经建好的对象,原样复制出来一个新对象,计数 + 1。 什么时候调用:用现成对象去初始化新对象,例子里 T t3(t2); 就是它。
移动构造函数:
把一个对象的数据转移给新对象(这里代码只是简单拷贝),计数 + 1。 什么时候调用:用 std::move 把对象转成右值来造新对象,也就是 T t4(std::move(t2)); 触发这个
析构函数:
对象不用了、要销毁的时候自动跑,对象总数减 1,做清理。 什么时候调用:局部对象跑出它所在的大括号范围,自动执行。
对应这四个对象: t1、t2 → 普通构造 t3 → 复制构造 t4 → 移动构造
问题2:

不能正常编译。 静态成员变量本来是写在 t.cpp 里的。 如果把这三行挪到头文件 t.h 最后: 头文件会被 t.cpp、task1.cpp 两个文件一起包含,相当于同一份变量定义写了两遍。编译器会报错:这个变量重复定义了。
问题3:
t1~t4 是写在 test 函数里面大括号{}里的局部变量。
作用域:只能在这个大括号里面用,括号外面看不见;
生命周期:进到括号的时候创建,一出括号就销毁,不能直接用t1访问m1,m2,m1、m2 标了 private 私有,外面的代码不能直接碰。 这就是封装:把数据藏起来,不让外面随便乱改,只能通过类里面给好的函数去操作,保护内部数据。
问题4:
throw就是主动抛出异常。就是:不能再新建对象了,直接报错通知外面。 如果外面没有写代码去接住这个错误,程序就直接停掉
改成2后运行结果:

改成 2 之后,最多只能同时存在 2 个对象: t1 创建(1 个)→ t2 创建(2 个),轮到造 t3 的时候,数量已经满了,触发 throw 抛异常。程序直接崩溃终止。 已经建好的 t1、t2 不会自动销毁。 原因:异常抛出来之后没人接住,程序直接强行结束,不会去自动调用析构函数清理 t1、t2。
task2:
Complex.h
#ifndef COMPLEX_H #define COMPLEX_H #include <string> class Complex { public: static const std::string doc; Complex(); Complex(double r); Complex(double r, double i); 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_; }; #endif
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::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 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); }
task.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:

① 要加 const 写在成员函数后面:double real() const 不加的话报错:不能再const对象上调用非const函数。 意思就是:c6 是 const 对象,承诺自己不会被修改,只能调用保证不改动对象的函数;不带 const 的函数编译器默认有可能改里面数据,不让调用。
② 编译不通过。 因为 add 函数会修改复数内部的数据而 c6 是 const 对象,初始化之后就不允许改里面数据。 这个就是const保护机制:const 对象禁止调用会修改自身的成员函数,防止数据被意外改动。
问题2:
标准库的写法更简洁。 自定义类要单独写 add、is_equal、output 这种函数;标准库直接用运算符 +、==、<<,写起来和普通数字一样。它们底层是有关系的:标准库这些运算符本质就是运算符重载,背后也是做复数实部虚部加减对比,和我们自定义 add、is_equal 干的活一模一样,只是包装成运算符形式
问题3:
① 不是必须写成友元。不用 friend 也能实现。 思路:给 Complex 写 public 的real()、imag()读取接口,普通函数直接调用这两个公开接口拿实部虚部计算,不用直接碰私有成员。友元只是方便直接访问私有变量,省掉调用 get 函数。
② std::complex 没有把abs设成友元。 cppreference 链接:https://en.cppreference.com/w/cpp/numeric/complex/abs std 的 abs 是普通非成员函数,靠 public 接口 real ()、imag () 获取数据,不是友元。
③ 工业场景 friend 使用尽量少用 friend。只有当外部函数 / 另一个类,需要频繁访问当前类私有成员,又不方便做成成员函数、也不想额外暴露一堆 get 接口时才考虑。比如运算符重载、跨类协作。它会破坏封装,优先用成员函数、公开接口方案
task3:
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) { // xxx } 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; }
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; };
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(); }
运行结果:

问题:
const成员函数的意思是:不修改这个对象的自己普通变量,不是不能改静态成员。 total_cnt是static静态成员,它不属于某一个对象,是整个类共享的变量,不归这个对象管。所以哪怕函数带const,照样可以写++total_cnt。
task4:
Fraction.h
#ifndef FRACTION_H #define FRACTION_H #include <string> #include <stdexcept> class Fraction { public: static inline const std::string doc = "Fraction类 v 0.01版.\n目前仅支持分数对象的构造、输出、加/减/乘/除运算."; 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; static int gcd(int a, int b); void reduce(); }; #endif
Fraction.cpp
#include "Fraction.h" #include <iostream> #include <cstdlib> 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"); // 符号统一:分母为正,负号放分子 if(down < 0) { up = -up; down = -down; } int g = gcd(up, down); if(g != 0) { up /= g; down /= g; } } 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"; try { test2(); } catch(const std::invalid_argument& e) { std::cout << e.what() << std::endl; } return 0; }
运行结果:

问题:
我选择方案一:分数类+友元函数。 理由: add、sub、mul、div、output 这些运算函数需要直接访问 Fraction 类里面私有成员up(分子)和down(分母)。如果不用友元,只能反复调用 get_up ()、get_down () 来拿数据,写起来啰嗦,代码可读性差。 友元函数可以直接读取私有分子分母,运算逻辑写得简洁直观,符合分数运算的调用形式add(f1,f2),和题目给的测试代码调用方式完全匹配,不用改动 task4.cpp 里的调用语句。 同时友元只是给函数开放访问权限,不会破坏类的封装,类的私有数据依然对外隐藏,只有指定的运算函数能够访问,适合这个分数运算的场景。

浙公网安备 33010602011771号