实验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类对象数目
};
const std::string T::doc{"a simple class sample"};
const int T::MAX_CNT = 999;
int T::current_cnt = 0;

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
点击查看代码
#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();
}

  • 运行测试截图

屏幕截图 2026-11-15 151735

  • 问题回答
    1.T(int x = 0, int y = 0); 普通构造函数,功能:初始化对象的成员变量;调用时机:直接创建新对象时(T t1;、T t1(1,2)),t1 一般触发这个。
    T(const T &t); 复制构造函数,功能:用已有对象拷贝一份新对象;调用时机:用旧对象初始化新对象 T t2 = t1;,t2 触发复制构造。
    T(T &&t);移动构造函数,功能:把临时对象的资源转移给新对象,避免拷贝开销;调用时机:接收右值 / 临时对象,T t3 = T(1,2),t3 触发移动构造。
    ~T();析构函数,功能:释放对象占用资源;调用时机:对象离开作用域销毁的时候自动调用;t1/t2/t3/t4 出作用域时都会触发析构。
    2.不能正确编译。

屏幕截图 2026-11-18 133937

原因:
const std::string T::doc、const int T::MAX_CNT、int T::current_cnt是类静态成员的定义(分配内存)。
类内只是声明,定义只能放 cpp 源文件;头文件会被多个文件#include,如果放到头文件末尾,多次包含会造成重复定义(multiple definition)链接报错。
3.作用域:t1、t2、t3、t4 是 test 函数内局部对象,作用域仅限 test 函数内部,函数外面不能访问。
生命期:进入 test 函数时构造创建,离开 test 函数时自动调用析构销毁。
在该作用域内:可以通过 t1 访问它自己的私有成员 m1、m2。
原理:访问控制是类级别,不是对象级别,同一个类的成员函数内,该类所有对象的私有成员都互相可见。
体现特性:封装。封装把数据和方法打包,对外隐藏内部细节,只开放指定接口。
4.throw用于抛出异常,会中断当前代码,向上寻找catch捕获。
MAX_CNT 改为 2,创建第 3 个对象时抛出异常;若无 catch 捕获,程序崩溃。
已经构造完成的 t1 等对象会正常析构,C++ 栈展开机制会自动销毁已构造完成的局部对象。

任务2

  • 源代码
    c.h
点击查看代码
#ifndef COMPLEX_H
#define COMPLEX_H

class Complex
{
private:
    double m_rea, m_imag;
public:
    static const char* doc;
    Complex();
    Complex(double r, double i = 0);
    Complex(const Complex &other);
    double real() const;
    double imag() const;
    Complex add(const Complex &b) const;
    friend void output(const Complex &c);
    friend bool is_equal(const Complex &a, const Complex &b);
    friend bool is_not_equal(const Complex &a, const Complex &b);
    friend double abs(const Complex &c);
};

#endif
c.cpp
点击查看代码
#include "Complex.h"
#include <iostream>
#include <cmath>
using namespace std;

const char* Complex::doc = "自定义复数类";

Complex::Complex() : m_rea(0), m_imag(0) {}

Complex::Complex(double r, double i) : m_rea(r), m_imag(i) {}

Complex::Complex(const Complex &other)
{
    m_rea = other.m_rea;
    m_imag = other.m_imag;
}

double Complex::real() const
{
    return m_rea;
}

double Complex::imag() const
{
    return m_imag;
}

Complex Complex::add(const Complex &b) const
{
    return Complex(m_rea + b.m_rea, m_imag + b.m_imag);
}

void output(const Complex &c)
{
    cout << c.m_rea;
    if (c.m_imag >= 0)
        cout << "+";
    cout << c.m_imag << "i";
}

double abs(const Complex &c)
{
    return sqrt(c.m_rea * c.m_rea + c.m_imag * c.m_imag);
}

bool is_equal(const Complex &a, const Complex &b)
{
    return a.m_rea == b.m_rea && a.m_imag == b.m_imag;
}

bool is_not_equal(const Complex &a, const Complex &b)
{
    return !(a.m_rea == b.m_rea && a.m_imag == b.m_imag);
}

task2
点击查看代码
#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 = c2.add(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();
}
  • 运行测试截图

屏幕截图 2026-11-18 141842

屏幕截图 2026-11-18 141851

  • 问题回答
    1.需要加const关键字,放在成员函数括号后面:double real() const;不加的话报错:不能在const对象上调用非const成员函数,this指针是const限定,无法绑定到非const成员函数。

不能编译通过。add()没有标记为const,编译器会认为它有可能修改对象内部数据;而c6是const对象,不允许调用可能修改自身的成员函数。
体现:const对象的只读保护机制,防止 const 对象被意外修改。

2.std::complex用法更简洁。
内在关联:运算符(+、==、!=、<<)本质上就是封装了对应的函数逻辑,底层等价于调用对应的函数。

3.不是必须设为友元。
可以不用friend:通过类提供的real()、imag()这类public成员接口读取实部虚部,不需要直接访问私有成员,就能实现一样功能。

std::complex的abs不是友元,它是普通非成员函数,依靠complex的公共接口取值。
cppreference 链接:https://en.cppreference.com/w/cpp/numeric/complex/abs

工业场景:仅当必须直接访问私有成员、又不适合增加公开接口时才用 friend;尽量少用,它会破坏封装性,优先使用public成员函数。

任务3

  • 源代码
    pc.cpp
点击查看代码
#include "PlayerControl.h"
#include <iostream>
#include <cctype>

int PlayerControl::total_cnt = 0;

PlayerControl::PlayerControl() {}

ControlType PlayerControl::parse(const std::string& control_str) {
    std::string s = control_str;
    
    for (int i = 0; i < s.size(); ++i) {
        s[i] = tolower(static_cast<unsigned char>(s[i]));
    }

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

pc.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
点击查看代码
#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();
}
  • 运行测试截图

屏幕截图 2026-11-18 144756

  • 问题回答
    const成员函数禁止修改对象的普通成员,但mutable修饰的成员变量不受const限制,total_cnt被mutable声明,因此可以修改。

任务4

  • 源代码
    Fraction.h
点击查看代码
#ifndef FRACTION_H
#define FRACTION_H

#include <string>
namespace frac
{
    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;

    private:
        int up;
        int down;
        void reduce(); 
    };

    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);
}
#endif

Fraction.cpp
点击查看代码
#include "Fraction.h"
#include <iostream>
#include <stdexcept>
#include <algorithm>
using namespace std;

namespace frac
{
    const string Fraction::doc = "Fraction类 v 0.01版.\n目前仅支持分数对象的构造、输出、加/减/乘/除运算.";

    static int gcd(int a, int b)
    {
        a = abs(a);
        b = abs(b);
        while(b != 0)
        {
            int r = a % b;
            a = b;
            b = r;
        }
        return a;
    }

    void Fraction::reduce()
    {
        if(down == 0)
            throw 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 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.get_down() == 1)
        {
            cout << f.get_up();
        }
        else
        {
            cout << f.get_up() << "/" << f.get_down();
        }
    }

    Fraction add(const Fraction& a, const Fraction& b)
    {
        int nu = a.get_up() * b.get_down() + b.get_up() * a.get_down();
        int de = a.get_down() * b.get_down();
        return Fraction(nu, de);
    }

    Fraction sub(const Fraction& a, const Fraction& b)
    {
        int nu = a.get_up() * b.get_down() - b.get_up() * a.get_down();
        int de = a.get_down() * b.get_down();
        return Fraction(nu, de);
    }

    Fraction mul(const Fraction& a, const Fraction& b)
    {
        int nu = a.get_up() * b.get_up();
        int de = a.get_down() * b.get_down();
        return Fraction(nu, de);
    }

    Fraction div(const Fraction& a, const Fraction& b)
    {
        int nu = a.get_up() * b.get_down();
        int de = a.get_down() * b.get_up();
        return Fraction(nu, de);
    }
}

task4
点击查看代码
#include <iostream>

#include "Fraction.h"

void test1() {
	using namespace frac;
    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 namespace frac;
    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();
}
  • 运行测试截图

屏幕截图 2026-11-18 152149

  • 问题回答
    选择方案 2:分数类+命名空间自由函数。理由:运算函数无需访问私有成员,不需要友元;使用命名空间组织相关代码,防止命名污染,结构清晰,适配题目给定的调用方式,便于后续扩展。
posted @ 2026-11-18 22:11  Rzzzr  阅读(2)  评论(0)    收藏  举报