实验二

任务一

源代码

#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

  • T t1;:触发 普通构造函数(使用了默认参数)。

  • T t2(3, 4);:触发 普通构造函数(带参数)。

  • T t3(t2);:触发 复制构造函数。

  • T t4(std::move(t2));:触发 移动构造函数。

问题2

不能,在 C++ 中,如果在头文件(.h)中直接定义静态成员变量并赋予初值,当这个头文件被多个源文件(.cpp)#include 时,每个源文件都会生成一份该变量的定义。在链接阶段,链接器会发现多个目标文件(.o)中存在同名的全局变量符号,从而导致重复定义(Multiple Definition)的链接错误。

问题3

  • t1, t2, t3, t4 均在 test() 函数内部的 {} 复合语句块中定义。它们的作用域仅限于这个 {} 内部(从定义处开始,到 } 结束)。

  • 它们的生命周期从各自被定义(构造)的那一刻开始,直到程序执行到该 {} 的右大括号 } 时结束(在此处依次调用析构函数销毁,销毁顺序与创建顺序相反,即 t4 -> t3 -> t2 -> t1)。

能否通过 t1 访问私有成员 m1、m2:
不能。

体现的特性:
体现了面向对象编程的封装性。类的private对外部隐藏,只能通过类的公有成员函数或者友元函数来进行受控的访问和操作。

问题4

throw 功能查询:
throw 是 C++ 的异常抛出机制。当程序遇到无法处理的错误时,可以使用 throw 抛出一个异常对象(这里抛出了 std::runtime_error)。这会立刻中断当前函数的执行,并将控制权沿着函数调用栈向上传递,直到找到匹配的 catch 块来处理该异常。

 

任务二

源代码

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

// 静态成员初始化(注意:类外初始化不需要再加 static 关键字)
const std::string Complex::doc = "a simplified Complex class";

// 构造函数实现
Complex::Complex(double r, double i) : real_(r), imag_(i) {}

// 接口实现
double Complex::real() const { 
    return real_; 
}

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

void Complex::add(const Complex &c) {
    real_ += c.real_;
    imag_ += c.imag_;
}

// 友元函数实现
void output(const Complex &c) {
    std::cout << c.real_;
    // 处理虚部的正负号,使得输出格式美观,如 "3 - 4i" 或 "3 + 4i"
    if (c.imag_ >= 0) {
        std::cout << " + " << c.imag_ << "i";
    } else {
        std::cout << " - " << -c.imag_ << "i"; 
    }
}

double abs(const Complex &c) {
    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 epsilon = 1e-9;
    return (std::abs(c1.real_ - c2.real_) < epsilon) && 
           (std::abs(c1.imag_ - c2.imag_) < epsilon);
}

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

#include <string>
#include <iostream>

class Complex {
// 友元函数声明
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);

public:
    // 公有静态常量成员
    static const std::string doc;
    
    // 构造函数(带默认参数,支持隐式转换)
    Complex(double r = 0.0, double i = 0.0); 

    // 接口
    double real() const;
    double imag() const;
    void add(const Complex &c);

private:
    double real_; // 实部
    double imag_; // 虚部
};

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

运行截图

{0C783849-E63E-44EC-B056-C9C9B54060C1}

 问题一

① 必须加的关键字与报错信息

为了让 c6.real() 和 c6.imag() 能通过编译,设计 Complex 类的成员函数时,必须在函数参数列表后加上 const 关键字(例如 double real() const;)。

如果不加,编译器会报错。这是因为 c6 是 const 对象,而 const 对象只能调用 const 成员函数,不能调用非 const 成员函数。

② c6.add(c2) 能否编译通过及原因

不能编译通过。 原因在于,作为 const 对象,c6 在初始化后不允许被修改。而 add() 成员函数的行为是修改自身的数据成员,这不符合 const 对象的约束。编译器会阻止对 const 对象调用可能修改其状态的成员函数。

这体现了类的封装与数据保护机制:通过 const 关键字,类设计者可以明确告知编译器哪些成员函数是“只读”的。const 对象只能调用 const 成员函数,从而防止对常量对象进行意外修改,保证了程序的常量正确性。

问题二

标准库模板类的使用形式更简洁。

存在内在关联。 

问题三

工业场景中何时考虑使用 friend

当非成员函数(尤其是运算符重载)需要高效访问私有数据、且无法通过公有接口优雅实现时,才考虑用 friend。它会削弱封装性,因此优先用成员函数或公有接口;仅在必须实现对称运算(如流输出 operator<<)、或与外部工具类紧密协作时,才作为受控的特例使用。

任务三

源代码

#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();
}
#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;   
};
#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 和 std::tolower 转换为小写
    std::transform(lower_str.begin(), lower_str.end(), lower_str.begin(), 
                   [](unsigned char c){ return std::tolower(c); });

    // 匹配字符串
    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;
}

 

运行截图

{DEF9079E-C193-4021-A62D-C6A9F832138F}

 问题回答

const 成员函数不能修改普通成员变量,但可以修改静态成员变量。

任务四

源代码

#include <iostream>
#include <stdexcept>

#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;
    
    // 使用 try-catch 捕获除数为0的异常,防止程序直接崩溃
    try {
        cout << "f6 / f7 = "; 
        output(div(f6, f7)); 
        cout << endl;
    } catch (const std::exception& e) {
        cout << "抛出异常: " << e.what() << endl;
    }
}

int main() {
    std::cout << "测试1: Fraction类基础功能测试\n";
    test1();

    std::cout << "\n测试2: 分母为0测试: \n";
    test2();
    
    return 0;
}
#ifndef FRACTION_H
#define FRACTION_H

#include <string>
#include <iostream>

class Fraction {
    // 声明工具函数为友元,以便它们能直接访问私有成员 up 和 down
    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);

public:
    static const std::string doc;

    // 构造函数,带默认参数,并支持隐式转换
    Fraction(int up = 0, int down = 1);

    // 接口
    int get_up() const;
    int get_down() const;
    Fraction negative() const;

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

    // 内部辅助函数
    void reduce(); 
    static int gcd(int a, int b);
};

#endif // FRACTION_H
#include "Fraction.h"
#include <stdexcept>
#include <cmath>
#include <cstdlib>

// 静态成员初始化
const std::string Fraction::doc = 
    "Fraction类 v 0.01版.\n"
    "目前仅支持分数对象的构造、输出、加/减/乘/除运算.";

// 构造函数
Fraction::Fraction(int u, int d) : up(u), down(d) {
    if (down == 0) {
        // 抛出异常处理分母为0的情况
        throw std::invalid_argument("Fraction: denominator cannot be zero.");
    }
    reduce(); // 构造时立刻约分并统一符号
}

// 接口实现
int Fraction::get_up() const { 
    return up; 
}

int Fraction::get_down() const { 
    return down; 
}

Fraction Fraction::negative() const {
    // 返回一个新对象,原对象 f1 保持不变
    return Fraction(-up, down);
}

// 私有辅助函数:求最大公约数
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::reduce() {
    if (up == 0) {
        down = 1; // 分子为0时,分母统一定为1
        return;
    }
    
    // 如果分母为负数,把负号移到分子上,保证分母始终为正
    if (down < 0) {
        up = -up;
        down = -down;
    }

    int divisor = gcd(up, down);
    up /= divisor;
    down /= divisor;
}

// ----------------- 友元函数实现 -----------------

void output(const Fraction &f) {
    std::cout << f.up << "/" << f.down;
}

Fraction add(const Fraction &f1, const Fraction &f2) {
    int new_up = f1.up * f2.down + f2.up * f1.down;
    int new_down = f1.down * f2.down;
    return Fraction(new_up, new_down);
}

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

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

Fraction div(const Fraction &f1, const Fraction &f2) {
    if (f2.up == 0) {
        // 除数为0的异常处理
        throw std::domain_error("Fraction division by zero!");
    }
    return Fraction(f1.up * f2.down, f1.down * f2.up);
}

运行截图

image

 问题回答

我选择的是 方案1:分数类 + 友元函数。

决策理由:直接访问私有数据,提高效率与简洁性,保持运算的对称性,更好的封装性

 
posted @ 2026-11-14 12:29  qrdx  阅读(14)  评论(0)    收藏  举报