实验2 类与对象

任务一

  • 源代码
    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();
}
  • 运行测试截图

21

  • 问题问答
    1.问题1:
    t.h中,line7-10给出了各种构造函数、析构函数。用文字简洁说明它们各自的功能、调用时机。结合t1-t4,说明它们分别触发了哪个构造函数。
    答:t1; → 普通构造函数(默认实参 x=0,y=0)
    t2(3,4); → 普通构造函数
    t3(t2); → 拷贝构造函数
    t4(std::move(t2)); → 移动构造函数

2.问题2:
t.cpp中,line8-10,剪切到t.h的末尾,重新编译,程序能否正确编译。如不能,以截图形式给出报错信息,分析原因。
报错:
1
答:静态数据成员类内只是声明,定义(初始化)只能放在源文件(cpp),头文件会被多个 cpp 包含(task1.cpp、t.cpp 都 include t.h),会造成重复定义,链接报错。

3.问题3:
类T的测试模块 test 中,说明对象 t1-t4 的作用域和生命期。并思考:在这个作用域内,能否通过 t1 访问其私有成员 m1、m2?这体现了类的什么特性?
答:对象 t1~t4 定义在 test 函数里面的一对内层大括号中:
作用域:仅在内层{}内部可见;出这个大括号,名字不可访问。
生命周期:进入{}时创建,离开这个内层右花括号时立刻销毁。
在作用域内,不能直接通过t1访问m1、m2 标记为private私有成员。
体现类的封装、信息隐藏特性:对象内部数据对外隐藏,只能通过类的成员函数、友元访问,外部不能直接读写私有成员。

4.问题4:
t.cpp中包含了头文件 #include ,构造函数中均使用了以下代码。使用搜索引擎/AI查询 throw功能。把t.cpp中T::MAX_CNT值改成2,重新编译、运行程序。观察输出,程序是正常结束还是崩溃了?给出截图运行结果。
会崩溃异常
2

如果崩溃了,已经创建的对象(如t1),会被正常销毁吗?给出答案,并说明理由。
已经成功构造完成的对象 t1、t2 会被正常销毁。
理由:C++ 异常的栈展开(stack unwinding)机制:抛出异常时,沿着栈向上回退,所有已经构造完毕、还没销毁的局部对象,会自动调用析构函数,释放资源;
而 t3 在构造函数内部抛出异常,t3 本身构造没有完成,t3 不会调用析构。

任务二

  • 源代码
    Complex.h
点击查看代码
#ifndef COMPLEX_H
#define COMPLEX_H
#include <string>

class Complex
{
public:
    static const std::string doc;
    Complex();
    Complex(double r);
    Complex(double r, double i);
    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& 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_;
};

#endif

Complex.cpp

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

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

Complex::Complex() : real_(0.0), imag_(0.0) {}

Complex::Complex(double r) : real_(r), 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)
{
    if (c.imag_ >= 0)
    {
        std::cout << c.real_ << " + " << c.imag_ << "i";
    }
    else
    {
        std::cout << c.real_ << " - " << -c.imag_ << "i";
    }
}

double abs(const Complex& c)
{
    return 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();
}
  • 运行测试截图

3

问题1:
在测试代码中,c6是cons对象。
① 为了让 c6.real() 和 c6.imag() 能编译通过,在设计 Complex 类的成员函数时,必须加上什么关键字?如果不加,编译器会报什么错?(请简述或截图报错信息)。
答:必须加 const关键字,写成 double real() const;double imag() const;。
不加报错:passing const Complex as this argument discards qualifiers,含义:const 对象不能调用非 const 成员函数。

② 作为const对象,c6在初始化后不允许再被修改。在测试代码中添加执c6.add(c2); ,能编译通过吗?为什么?这体现了类的什么保护机制?
答:不能编译通过。add会修改对象成员,它不是const成员函数;const对象只能调用 const 成员函数。体现const常量保护机制,防止只读对象被意外修改。

问题2:
比较自定义类 Complex 和标准库模板类 complex 的用法,在使用形式上,哪种更简洁?据此推断函数和运算是否存在内在关联呢?
答:std::complex使用形式更简洁。
内在关联:标准库使用运算符重载,把运算语义绑定到 + += == != 等运算符,写法贴近数学表达式;自定义版本用独立函数调用,语法繁琐。运算符重载本质就是特殊的函数。

问题3:
① 本练习中, output 、 abs 、 add (非成员版本)等被设为Complex的友元。这是必须的吗?如果将其声明为普通非成员函数(不用 friend ),能否实现相同的功能?简述思路。
不是必须为友元。可以不用 friend:借助real()、imag()这两个公有const接口读取实部虚部,普通非成员函数一样实现全部功能,不需要直接访问私有成员。

② 标准库 std::complex 是否把 abs 设为友元?(查阅 cppreference后回答,并提供页面具体链接地址)
std::complex 的abs不是友元。
链接地址:https://en.cppreference.com/w/cpp/numeric/complex/abs

③ 工业场景中,什么时候才考虑使用 friend ?和AI讨论后,简洁概括你的思考和结论。
friend 仅在需要直接访问私有成员、又不适合新增公有接口时使用。优先依靠公有成员接口实现功能;友元会破坏封装,缩小访问控制的隔离范围,尽量少用。

任务三

  • 源代码
    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);
    void execute(ControlType cmd) const;
    static int get_cnt();
private:
    static int total_cnt;
};

PlayerControl.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;
    for (char ch : control_str)
    {
        s += static_cast<char>(tolower(ch));
    }
    if (s == "play")    return ControlType::Play;
    if (s == "pause")   return ControlType::Pause;
    if (s == "next")    return ControlType::Next;
    if (s == "prev")    return ControlType::Prev;
    if (s == "stop")    return ControlType::Stop;
    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;
}

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

  • 运行测试截图

4

  • 问题回答
    接口void execute(ControlType cmd) const; 是const成员函数,为什么在其内部实现允许代码++total_cnt?
    答:const成员函数的含义:不修改本对象的非静态成员变量。total_cnt是静态成员变量,属于整个类,不属于某一个实例对象,不受这个const限制,所以可以修改。

选:如果希望模拟播放控制时,输出控制更现代(使用emoji),如何调整代码实现?
答:直接修改execute里面cout输出内容

点击查看代码
case ControlType::Play:
    std::cout << "▶️ Playing music...\n";
    break;
case ControlType::Pause:
    std::cout << "⏸️ Music paused\n";
    break;
case ControlType::Next:
    std::cout << "⏭️ Skipping to next track\n";
    break;
case ControlType::Prev:
    std::cout << "⏮️ Back to previous track\n";
    break;
case ControlType::Stop:
    std::cout << "⏹️ Music stopped\n";
    break;

任务四

  • 源代码
    Fraction.h
点击查看代码
#pragma once
#include <string>
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;

    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 reduce();
    static int gcd(int a, int b);
};

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

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

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

void Fraction::reduce()
{
    if(up == 0)
    {
        down = 1;
        return;
    }
    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 std::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)
{
    std::cout << f.up << "/" << f.down;
}

Fraction add(const Fraction& a, const Fraction& b)
{
    int nu = a.up * b.down + b.up * a.down;
    int de = a.down * b.down;
    return Fraction(nu, de);
}
Fraction sub(const Fraction& a, const Fraction& b)
{
    int nu = a.up * b.down - b.up * a.down;
    int de = a.down * b.down;
    return Fraction(nu, de);
}
Fraction mul(const Fraction& a, const Fraction& b)
{
    int nu = a.up * b.up;
    int de = a.down * b.down;
    return Fraction(nu, de);
}
Fraction div(const Fraction& a, const Fraction& b)
{
    int nu = a.up * b.down;
    int de = a.down * b.up;
    return Fraction(nu, de);
}

task4.cpp

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

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";
    try
    {
        test1();
    }
    catch(...)
    {}
    std::cout << "\n测试2: 分母为0测试: \n";
    try
    {
        test2();
    }
    catch(const std::invalid_argument& e)
    {
        std::cout << "异常捕获:" << e.what() << std::endl;
    }
    return 0;
}

  • 运行测试截图

5

  • 问题问答:
    分数运算(output/add/sub/mul/div),你选择的是哪种设计方案?你的决策理由?
    答:选择:方案1:分数类 + 友元函数
    决策理由:题目测试代码直接使用add(f1,f2)、output(f1)的调用形式,友元函数可以直接访问私有成员 up、down,运算代码简洁;不需要额外写命名空间、不用修改测试代码。虽然友元会一定程度弱化封装,但适合这种简单运算工具函数,代码直观,匹配实验给的测试接口风格。

实验总结

本次实验完成播放器控制、分数Fraction两个多文件面向对象程序,掌握头文件与源文件分离的开发方式,理解#pragma once的作用。我厘清了const成员函数的特点:它不能修改对象普通成员,但静态成员属于类本身,不受const限制。学习强类型枚举enum class,实现大小写无关的命令解析。在分数类中对比友元、命名空间自由函数两种方案,明白友元使用便捷但会削弱封装。

posted @ 2026-11-18 19:37  ZoooY  阅读(7)  评论(0)    收藏  举报