实验二

实验2 类和对象_基础编程1

任务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();
}
  • task1运行截图

屏幕截图 2026-11-13 113231

  • 问题1
    T(int x = 0, int y = 0):普通构造函数。在创建新对象并传入初始值时调用。t1 和 t2 触发了该构造函数。
    T(const T &t):复制构造函数。在用一个已存在的对象去初始化另一个新对象时调用。t3(t2) 触发了该构造函数。
    T(T &&t):移动构造函数。在用一个右值初始化新对象时调用。t4(std::move(t2)) 触发了该构造函数。
    ~T():析构函数。在对象生命周期结束时自动调用。t1 到 t4 在 test() 函数的内层作用域结束时调用。
  • 问题2

屏幕截图 2026-11-17 190130
原因分析:"重定义",头文件 t.h 被多个源文件包含。如果静态成员的定义放在头文件中,那么每个包含该头文件的源文件都会生成一份该变量的定义。链接时,链接器会发现多个相同的符号定义,从而报错。

  • 问题3
    作用域与生命期:t1 至 t4 的作用域均被限制在 test() 函数内。它们的生命期从定义处开始,到test()结束运行时结束。
    能否通过 t1 访问私有成员:不能。m1 和 m2 是 T 类的 private 成员。在类外,无法通过对象 t1 直接访问它们。
    体现的特性:这体现了类的封装。类将数据和操作数据的方法捆绑在一起,并限制外部对内部数据的直接访问,只暴露必要的接口,从而保护数据的完整性。
  • 问题4

屏幕截图 2026-11-17 191206

会被正常销毁。
理由:当异常被抛出且未被当前作用域捕获时,程序会开始退出当前作用域,并自动调用该作用域内所有已完全构造的局部对象的析构函数,以保证资源被正确释放。因此,t1 和 t2 的析构函数会在此过程中被调用。

任务2

  • Complex.h源代码
点击查看代码
#pragma once

#include <string>

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

    Complex(double r = 0.0, double i = 0.0);
    Complex(const Complex &c);

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

    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_;
};
+ Complex.cpp源代码
点击查看代码
#include "Complex.h"

#include <cmath>
#include <iostream>

// 静态常量成员:类内声明,类外初始化
const std::string Complex::doc{"a simplified Complex class"};

// 普通构造函数(同时充当默认构造函数)
Complex::Complex(double r, double i) : real_{r}, imag_{i} {}

// 复制构造函数
Complex::Complex(const Complex &c) : real_{c.real_}, imag_{c.imag_} {}

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

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

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

// 友元:输出 a+bi 形式
void output(const Complex &c) {
    std::cout << c.real_ << " + " << c.imag_ << "i";
}

// 友元:取模
double abs(const Complex &c) {
    return std::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);
}
+ 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();
}
+ 运行截图

屏幕截图 2026-11-17 195834

  • 问题1
    ① 必须加的关键字:const。real() 和 imag() 的声明和定义末尾都必须加上 const。
    不加的报错:编译器会报错,提示“将‘const Complex’作为‘this’参数传递给‘double Complex::real()’会丢弃限定符”(discards qualifiers)。因为 const 对象只能调用 const 成员函数。
    ② 不能编译通过。
    原因:c6 是 const 对象,而 add() 成员函数会修改对象自身的状态,因此它不能被声明为 const 成员函数。const 对象无权调用非 const 成员函数。
    体现的保护机制:这体现了常对象保护机制。通过 const 关键字,在编译期强制保证 const 对象在初始化后其状态不会被任何成员函数意外修改。
  • 问题2
    标准库 std::complex 的用法更简洁。它通过运算符重载让自定义类型的用法与内置类型保持一致,代码更直观。
    内在关联:自定义类中的 add、is_equal 等函数,在标准库中通常被实现为重载的运算符或非成员函数。例如,c1.add(c2) 对应 operator+=,add(c1, c2) 对应 operator+。函数与运算符在底层逻辑上是统一的,运算符本质上是具有特殊名字的函数。
  • 问题3
    ① 不是必须的。如果 output、abs、add 等函数不需要直接访问 Complex 的私有成员 real 和 imag,那么完全可以通过公有接口 real() 和 imag() 来获取数据,无需声明为友元。但在本设计中,为了直接访问私有数据以提高效率或简化代码,将其设为友元。
    不用 friend 的实现思路:在函数内部调用公有的 c.real() 和 c.imag() 来获取实部和虚部进行计算或输出。

② 不是。在 C++ 标准库中,std::abs(const complex&) 是一个非成员函数,它通过调用 complex 的公有成员函数 real() 和 imag() 来计算模长。 https://en.cppreference.com/w/cpp/numeric/complex/abs 。

③ 当非成员函数(如运算符重载 operator<<、operator>>)或辅助函数在逻辑上属于类接口的一部分,且必须直接访问私有数据才能高效或自然地实现时,才考虑用 friend。典型场景是流操作符重载,因为它需要访问对象的内部表示来格式化输出。滥用 friend 会破坏封装,应优先通过公有接口解决问题。

任务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 str = control_str;
    
    // 统一转为小写
    std::transform(str.begin(), str.end(), str.begin(), ::tolower);
    
    // 匹配并返回对应的枚举值
    if (str == "play")  return ControlType::Play;
    if (str == "pause") return ControlType::Pause;
    if (str == "next")  return ControlType::Next;
    if (str == "prev")  return ControlType::Prev;
    if (str == "stop")  return ControlType::Stop;
    
    // 未匹配的字符串
    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();
    return 0;
}
  • 运行截图

屏幕截图 2026-11-18 193346

  • 问题
    因为 const 成员函数承诺不修改该对象的非静态数据成员。而 total_cnt 是静态数据成员,它属于类本身,不属于任何一个具体的对象。const 对静态成员没有约束力,因此在 const 成员函数中修改静态成员是允许的。

任务4

  • Fraction.h源代码
点击查看代码
#pragma once

#include <string>

class Fraction {
public:
    // 类属性:说明信息
    static const std::string doc;

    // 构造函数
    Fraction(int up0 = 0, int down0 = 1);
    Fraction(const Fraction &f);

    // 接口
    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;    // 分母

    // 内部辅助函数:化简分数并统一符号(分子承载符号)
    void simplify();
};

// 辅助:求最大公约数
int gcd(int a, int b);
  • Fraction.cpp源代码
点击查看代码
#include "Fraction.h"
#include <iostream>
#include <stdexcept>
#include <cstdlib> // std::abs

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

// 求最大公约数 (辗转相除法)
int 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) return; // 已经抛出异常或未初始化
    if (up == 0) {
        down = 1;
        return;
    }
    // 保证负号在分子上
    if (down < 0) {
        up = -up;
        down = -down;
    }
    int d = gcd(up, down);
    up /= d;
    down /= d;
}

// 构造函数
Fraction::Fraction(int up0, int down0) : up(up0), down(down0) {
    if (down == 0) {
        throw std::invalid_argument("Fraction: 分母不能为0");
    }
    simplify();
}

// 复制构造函数
Fraction::Fraction(const Fraction &f) : up(f.up), down(f.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";
    test2();
    return 0;
}
  • 运行截图

屏幕截图 2026-11-18 194311

  • 问题
    我选择的是方案1
    理由:
  1. 更契合封装与数据保护
    分数类 Fraction 的分子 up 和 down 是私有成员。在进行加、减、乘、除运算时,需要大量直接读取或计算分子和分母。使用 友元函数 允许这些运算函数直接访问私有数据,避免了为了计算而被迫将内部数据暴露为 public,很好地平衡了数据共享与数据保护。
  2. 代码更简洁直观,降低维护成本
    使用友元函数时,可以直接在类内部声明运算函数,让使用者一目了然该类支持哪些外部运算。
posted @ 2026-11-18 19:48  徐玮伦  阅读(4)  评论(0)    收藏  举报