实验二

实验2

Task1:

#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 << ")";
}
#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类对象数目
};
#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();
}

运行结果截图

Task1

回答问题:

  问题1:1.line 7 是构造一个普通构造函数  line8是一个复制构造函数   line9是一个移动构造函数      line10是一个析构函数

问题2:把t.cpp 中的line8~line10放到t.h的末尾,仍能够运行程序 ,程序的运行结果:Task1截图

问题3:t1~t4的作用域为提到的函数以及主函数,生命周期与函数的生命周期相等,当函数的生命周期结束,其生命周期也会随着一同结束,能够访问类T的私有成员,其体现了类的封装性的特性

问题四:throw的作用:核心作业抛出异常与中断流程  2.异常对象的生命周期与生成  3.出发栈展开        当MAX_CNT的值改为2时,仍然可以运用,结果:MAX_CNT改为2结果

Task 2

代码:

 
#ifndef COMPLEX_H
#define COMPLEX_H

#include <string>
#include <iostream>

class Complex {
private:
    double real_; // 私有实部
    double imag_; // 私有虚部

public:
    // 类公有静态常量属性:类说明文档
    static const std::string doc;

    // 构造函数
    Complex(); // 0+0i 默认构造
    Complex(double r, double i = 0.0); // 支持单参数/双参数构造,允许隐式转换适配 Complex c6 = 3.5
    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& 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);
};

#endif
#include "Complex.h"
#include <cmath>
#include <iostream>

// 初始化类静态常量属性
const std::string Complex::doc = "a simplified complex class";

// 构造函数实现
Complex::Complex() : real_(0.0), 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) {
    // 格式化输出 a+bi 风格,虚部为负时自动转为 a - bi
    if (c.imag_ >= 0) {
        std::cout << c.real_ << " + " << c.imag_ << "i";
    } else {
        std::cout << c.real_ << " - " << -c.imag_ << "i";
    }
}

double abs(const Complex& c) {
    // 复数模长公式 sqrt(实部² + 虚部²)
    return std::sqrt(c.real_ * c.real_ + c.imag_ * c.imag_);
}

Complex add(const Complex& c1, const Complex& c2) {
    return Complex(c1.real_ + c2.real_, c1.imag_ + c2.imag_);
}

bool is_equal(const Complex& c1, const Complex& c2) {
    // 浮点数比较用极小epsilon避免精度误差
    const double EPS = 1e-9;
    return (std::abs(c1.real_ - c2.real_) < EPS) && (std::abs(c1.imag_ - c2.imag_) < EPS);
}

bool is_not_equal(const Complex& c1, const Complex& c2) {
    return !is_equal(c1, c2);
}
#include "Complex.h"
#include <cmath>
#include <iostream>

// 初始化类静态常量属性
const std::string Complex::doc = "a simplified complex class";

// 构造函数实现
Complex::Complex() : real_(0.0), 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) {
    // 格式化输出 a+bi 风格,虚部为负时自动转为 a - bi
    if (c.imag_ >= 0) {
        std::cout << c.real_ << " + " << c.imag_ << "i";
    } else {
        std::cout << c.real_ << " - " << -c.imag_ << "i";
    }
}

double abs(const Complex& c) {
    // 复数模长公式 sqrt(实部² + 虚部²)
    return std::sqrt(c.real_ * c.real_ + c.imag_ * c.imag_);
}

Complex add(const Complex& c1, const Complex& c2) {
    return Complex(c1.real_ + c2.real_, c1.imag_ + c2.imag_);
}

bool is_equal(const Complex& c1, const Complex& c2) {
    // 浮点数比较用极小epsilon避免精度误差
    const double EPS = 1e-9;
    return (std::abs(c1.real_ - c2.real_) < EPS) && (std::abs(c1.imag_ - c2.imag_) < EPS);
}

bool is_not_equal(const Complex& c1, const Complex& c2) {
    return !is_equal(c1, c2);
}

 

运行结果:

问题1:必须加上Complex::Complex(double r,double i) real_r,imag_(i)

否则的话会显示real和imag不存在

2:编译不能通过,因为const是固定的,不可以改变,体现了类的封装性

问题2:标准const库使用更加简洁,自定义类Complex库和标准库类模板存在关联,观察表格可以发现自定义类和标准库中的部分成员的作用可以一一对应

问题3:1.不是必须的,add,output,abs等的内容都可以用+,-等符号运算解决;不可以,如果将声明变为普通非成员函数,那么类的内部和外部都将变得私有,普通非成员函数不能访问私有成员;

2.std::complex没有将abs变为友元          

3.场景:1.运算符重载  2.工厂模式与私有构造函数  3.紧密协作的类  4.序列化与反序列化   5.性能敏感的数学/图形库

 

Task  3:

代码:

#include "PlayerControl.h"

#include <algorithm>  
#include <iostream>

int PlayerControl::total_cnt = 0;

PlayerControl::PlayerControl() {}

ControlType PlayerControl::parse(const std::string& control_str){
    
// 待补足
// 1. 将输入字符串统一成转为小写,实现大小写不敏感
std::string lower_str=control_str;
std::transform(lower_str.begin(),lower_str.end(),lower_str.begin(),[](unsigned char c){return std::tolower(c);});
// 2. 匹配"play"/"pause"/"next"/"prev"/"stop"并返回对应枚举;
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;
}
}
//    未匹配的字符串返回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;
}
#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();
}

运行结果:task3

问题一:const的作用:将隐含的this指针转变为const指针,禁止修改非静态成员变量,禁止调用const成员函数,而void exewcute(ControlType cmd)是一个静态函数,不受const的禁止作用

问题2:c++本身不支持将其转变为图标的形式,可以使用Unicode字符来实现将next等命令以图标的形式出现

task4:
代码:

#ifndef FRACTION_H
#define FRACTION_H

#include <string>
#include <iostream>
#include <stdexcept>

class Fraction {
private:
    int up;   // 分子
    int down; // 分母

    // 内部辅助函数:求最大公约数
    static int gcd(int a, int b);
    
    // 内部辅助函数:化简分数并规范符号
    void simplify();

public:
    // 类属性:文档说明
    static const std::string doc;

    // --- 构造函数 ---
    
    // 默认构造?题目未明确要求默认构造,但通常建议提供。
    // 题目要求支持:Fraction f1(2); -> 分母为1
    explicit Fraction(int up, int down = 1);

    // 拷贝构造:Fraction f3(f2);
    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& f1, const Fraction& f2);

    // 减法
    friend Fraction sub(const Fraction& f1, const Fraction& f2);

    // 乘法
    friend Fraction mul(const Fraction& f1, const Fraction& f2);

    // 除法
    friend Fraction div(const Fraction& f1, const Fraction& f2);
};

#endif // FRACTION_H
#include "Fraction.h"
#include <cmath>
#include <numeric> // for std::gcd in C++17, or use custom implementation

// 初始化静态常量成员
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::simplify() {
    if (down == 0) {
        // 理论上构造函数已检查,这里作为防御性编程
        throw std::invalid_argument("Fraction: 分母不能为0");
    }

    // 处理符号:保证分母为正,负号由分子承担
    if (down < 0) {
        up = -up;
        down = -down;
    }

    // 化简
    if (up != 0) {
        int common = gcd(up, down);
        up /= common;
        down /= common;
    } else {
        // 分子为0时,分母统一为1 (可选,视具体需求,通常 0/1 或 0/n 都行,这里统一为 0/1)
        down = 1;
    }
}

// --- 构造函数实现 ---

Fraction::Fraction(int up, int down) : up(up), down(down) {
    if (down == 0) {
        throw std::invalid_argument("Fraction: 分母不能为0");
    }
    simplify(); // 构造时立即化简
}

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& f1, const Fraction& f2) {
    int newUp = f1.up * f2.down + f2.up * f1.down;
    int newDown = f1.down * f2.down;
    return Fraction(newUp, newDown); // 构造函数会自动化简
}

Fraction sub(const Fraction& f1, const Fraction& f2) {
    int newUp = f1.up * f2.down - f2.up * f1.down;
    int newDown = f1.down * f2.down;
    return Fraction(newUp, newDown);
}

Fraction mul(const Fraction& f1, const Fraction& f2) {
    int newUp = f1.up * f2.up;
    int newDown = f1.down * f2.down;
    return Fraction(newUp, newDown);
}

Fraction div(const Fraction& f1, const Fraction& f2) {
    if (f2.up == 0) {
        throw std::invalid_argument("Fraction: 除数不能为0");
    }
    // 除以分数等于乘以倒数
    int newUp = f1.up * f2.down;
    int newDown = f1.down * f2.up;
    return Fraction(newUp, newDown);
}
#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;
    try {
        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;
    } catch (const std::invalid_argument& e) {
        cout << "Error: " << e.what() << endl;
    }
    
    // 测试分母为0的构造异常
    try {
        Fraction f_bad(1, 0);
    } catch (const std::invalid_argument& e) {
        cout << "Construction Error: " << e.what() << endl;
    }
}

int main() {
    std::cout << "测试1: Fraction类基础功能测试\n";
    test1();
    std::cout << "\n测试2: 分母为0测试: \n";
    test2();
    return 0;
}

输出结果:

屏幕截图 2026-11-16 163405

回答:

方案一:理由:能直接访问私有成员,内部封闭性更好,能动用simplify函数,完成标准化处理,既能保证所有运算结果始终合法,又不会对外泄露内部实现细节;

posted @ 2026-11-16 16:50  00卓  阅读(2)  评论(0)    收藏  举报