实验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); // 友元, 以(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:
  • line7是带默认值的普通构造函数,用给定参数初始化对象
  • line8是复制构造函数,用已有对象的数据初始化新对象,即复制构造
  • line9是移动构造函数,用可绑定到右值引用的对象初始化新对象,即移动构造
  • line10是析构函数,在对象销毁时执行清理
    t1、t2触发普通构造,t3触发复制构造,t4触发移动构造
问题2:

不能正确编译,报错信息:

问题2报错截图
关键报错包括:

multiple definition of `T::doc[abi:cxx11]'
multiple definition of `T::MAX_CNT'
multiple definition of `T::current_cnt'
collect2.exe: error: ld returned 1 exit status

t.cpp和task1.cpp都包含t.h,因此各自的翻译单元中都出现了这些非inline静态数据成员的定义,链接时违反了单一定义规则,因此会在链接阶段报错。

问题3:

这4个局部对象都定义在test()的内层花括号中。各名字的作用域从其声明处延续到该代码块结束,出了代码块就不能再使用这些名字。
即使在t1的作用域内,也不能在普通测试函数中直接写t1.m1或t1.m2,因为这两个成员为private。对象名可见不代表其所有成员均可访问,这体现了类的封装性与访问权限控制。

问题4:

throw 用于抛出异常,将正常执行流程转交给异常处理机制。例如 throw std::runtime_error(...) 构造并抛出运行时错误,异常处理机制会寻找匹配的 catch。抛出后不会继续执行当前构造函数中后面的计数递增和输出语句。

如果把t.cpp中T::MAX_CNT值改成2,程序会崩溃:

问题4崩溃截图
T: maximum object count exceeded说明进程异常终止了。
t1、t2会被正常销毁,因为抛异常前t1、t2就已经构造好了,会自动按照逆序调用析构函数销毁

实验任务2

源代码

Complex.h

点击查看代码
#pragma once

#include <string>

class Complex
{
public:
    Complex();
    Complex(double r);
    Complex(double r, double i);
    ~Complex();

    static const std::string doc;
    double real() const { return re; }
    double imag() const { return im; }
    void add(const Complex &other)
    {
        re += other.re;
        im += other.im;
    }

    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 re, im;
};

Complex.cpp

点击查看代码
#include <cmath>
#include <iostream>
#include <string>
#include "Complex.h"

const std::string Complex::doc = "a simplified complex class";

Complex::Complex() : re(0), im(0) {}
Complex::Complex(double r) : re(r), im(0) {}
Complex::Complex(double r, double i) : re(r), im(i) {}
Complex::~Complex() {}

void output(const Complex &c)
{
    std::cout << c.re << (c.im>=0 ? " + " : " - ") << (c.im>=0 ? c.im : -c.im) << "i" << std::endl;
}

double abs(const Complex &c)
{
    return std::sqrt(c.re * c.re + c.im * c.im);
}

Complex add(const Complex &c1, const Complex &c2)
{
    return Complex(c1.re + c2.re, c1.im + c2.im);
}

bool is_equal(const Complex &c1, const Complex &c2)
{
    return (c1.re == c2.re) && (c1.im == c2.im);
}

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:

①
必须在成员函数参数列表之后加 const,将它们声明为常成员函数,否则会报错:

问题1报错截图
图中的关键报错为:

error: passing 'const Complex' as 'this' argument discards qualifiers

不能把const对象传给非const成员函数,编译器因此报错
②
不能。c6 是常量对象,初始化后不能通过普通修改接口改变其状态;add 会执行 re += ...、im += ...,是非 const 成员函数,因此不能通过 c6 调用。该限制体现了类的常量对象保护机制。

问题2:

标准库的运算符写法更简洁,也更接近数学表达。
函数和运算符存在内在关联。对类类型,C++ 可以用运算符重载函数定义 “+”、“+=”、“==”、“<<” 等运算的含义。因此这些运算可以对应成员函数或非成员函数调用。

问题3:

①
不必须。当前实现直接访问 re、im,因此需要 friend 授权;如果改为通过公有的 real()、imag() 获取数值,同样可以完成输出、求模、相加和比较。
②
从标准公开接口看,std::abs(const std::complex<T>&) 是定义于 <complex> 的非成员函数模板,标准没有要求把它设为 std::complex 的友元。查阅的具体页面为 cppreference:std::abs(std::complex)
③
优先使用公有接口。只有函数或类与某个类型紧密协作,确需访问内部状态,且新增公开接口会暴露实现细节或破坏封装时,才考虑友元,例如需要内部访问的运算符或协作类。

实验任务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() {}

// 待补足
// 1. 将输入字符串统一成转为小写,实现大小写不敏感
// 2. 匹配"play"/"pause"/"next"/"prev"/"stop"并返回对应枚举;
//    未匹配的字符串返回ControlType::Unknown
ControlType PlayerControl::parse(const std::string& control_str) {
    std::string lower_str = control_str;
    std::transform(lower_str.begin(), lower_str.end(), lower_str.begin(), ::tolower);
    
    if (lower_str == "play") {
        return ControlType::Play;
    } else if (lower_str == "pause") {
        return ControlType::Pause;
    } else if (lower_str == "next") {
        return ControlType::Next;
    } else if (lower_str == "prev") {
        return ControlType::Prev;
    } else if (lower_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 "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 数据成员,属于整个类,由所有对象共享,不是当前对象内部独立保存的数据,因此不受这一限制。

实验任务4

源代码(采用C++17标准)

Fraction.h

点击查看代码
#pragma once

#include <string>

class Fraction
{
public:
    static const std::string doc;

    Fraction(int up = 0, int down = 1); // 构造函数,默认构造为0/1
    Fraction(const Fraction &other);    // 拷贝构造函数
    ~Fraction();                        // 析构函数

    int get_up() const;
    int get_down() const;
    Fraction negative() const;

private:
    int up;   // 分子
    int down; // 分母

    void simplify(); // 约分,并保证分母为正
};

namespace frac
{
    void output(const Fraction &f);
    Fraction add(const Fraction a, const Fraction b);
    Fraction sub(const Fraction a, const Fraction b);
    Fraction mul(const Fraction a, const Fraction b);
    Fraction div(const Fraction a, const Fraction b);
}

Fraction.cpp

点击查看代码
#include <stdexcept>
#include <numeric>
#include <iostream>
#include "Fraction.h"

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 &other) : up{other.up}, down{other.down} {}

Fraction::~Fraction() {}

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) { 
        // 分母恒为正
        up = -up;
        down = -down;
    }
    int g = std::gcd(up < 0 ? -up : up, down);
    if (g > 1) {
        up /= g;
        down /= g;
    }
}

namespace frac
{
    void output(const Fraction &f)
    {
        std::cout << f.get_up();
        if (f.get_down() != 1)
            std::cout << '/' << f.get_down();
    }

    Fraction add(const Fraction a, const Fraction b)
    {
        return Fraction(a.get_up() * b.get_down() + b.get_up() * a.get_down(),
                        a.get_down() * b.get_down());
    }

    Fraction sub(const Fraction a, const Fraction b)
    {
        return Fraction(a.get_up() * b.get_down() - b.get_up() * a.get_down(),
                        a.get_down() * b.get_down());
    }

    Fraction mul(const Fraction a, const Fraction b)
    {
        return Fraction(a.get_up() * b.get_up(), a.get_down() * b.get_down());
    }

    Fraction div(const Fraction a, const Fraction b)
    {
        if (b.get_up() == 0)
            throw std::invalid_argument("Fraction: 除数不能为0");
        return Fraction(a.get_up() * b.get_down(), a.get_down() * b.get_up());
    }
}

task4.cpp

点击查看代码
#include <iostream>

#include "Fraction.h"
using namespace frac;

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();
}

运行截图

运行截图

问题回答

我选择方案2:分数类 + 命名空间自由函数。源码中 output/add/sub/mul/div 均位于 namespace frac 内,类中没有为它们声明友元。
选择这一方案的理由是:

  1. 公有的 get_up()、get_down() 已能提供运算所需数据,无须授予外部函数访问私有成员的权限。
  2. 类负责有效分数的表示、约分和符号规则;自由函数负责在两个分数之间计算,职责清楚。
  3. frac 命名空间集中组织分数工具函数,便于与其他模块的同名函数区分。
posted @ 2026-11-18 20:10  Robin酱  阅读(5)  评论(0)    收藏  举报