NUIST-OOP-Lab02

🧪 实验报告

一、实验名称

现代C++编程初体验

二、实验目的

  • 加深对OOP概念(类、对象)和特性(封装)的理解
  • 会用C++正确定义、实现、测试类;会创建对象,并基于对象编程
  • 加深对C++内存资源管理技术的理解,能够解释构造函数、析构函数的用途,分析它们何时会被调用
  • 会用多文件方式组织代码
  • 针对具体问题场景,练习运用面向对象思维设计,合理利用C++语言特性(封装与访问权限控制, static, friend,const),在数据共享和保护之间达到平衡

三、实验环境

项目 内容
操作系统 Ubuntu24.04
编译器/IDE g++13.3.0, clang13.3.0
编辑器 cursor, fish
实验日期 25/10/2025

四、实验内容与步骤

实验任务1

  • 源码与运行测试截图

[!WARNING]

乱码警告,出现乱码的原因见末尾解释

#pragma once

#include <string>

// ��T: ����
class T {
// �������ԡ�����
public:
    T(int x = 0, int y = 0);   // ��ͨ���캯��
    T(const T &t);  // ���ƹ��캯��
    T(T &&t);       // �ƶ����캯��
    ~T();           // ��������

    void adjust(int ratio);      // ��ϵ���ɱ���������
    void display() const;           // ��(m1, m2)��ʽ��ʾT�������Ϣ

private:
    int m1, m2;

// �����ԡ�����
public:
    static int get_cnt();          // ��ʾ��ǰT���������

public:
    static const std::string doc;       // ��T��������Ϣ
    static const int max_cnt;           // ��T��������

private:
    static int cnt;         // ��ǰT�������Ŀ

// ��T��Ԫ��������
    friend void func();
};

// ��ͨ��������
void func();

int T::get_cnt() {
   return cnt;
}
// T.cpp
#include "T.h"
#include <iostream>
#include <string>

// ��Tʵ��

// static��Ա���������ʼ��
const std::string T::doc{"a simple class sample"};
const int T::max_cnt = 999;
int T::cnt = 0;

// �෽��
// int T::get_cnt() {
//    return cnt;
// }

// ���󷽷�
T::T(int x, int y): m1{x}, m2{y} { 
    ++cnt; 
    std::cout << "T constructor called.\n";
} 

T::T(const T &t): m1{t.m1}, m2{t.m2} {
    ++cnt;
    std::cout << "T copy constructor called.\n";
}

T::T(T &&t): m1{t.m1}, m2{t.m2} {
    ++cnt;
    std::cout << "T move constructor called.\n";
}    

T::~T() {
    --cnt;
    std::cout << "T destructor called.\n";
}           

void T::adjust(int ratio) {
    m1 *= ratio;
    m2 *= ratio;
}    

void T::display() const {
    std::cout << "(" << m1 << ", " << m2 << ")" ;
}     

// ��ͨ����ʵ��
void func() {
    T t5(42);
    t5.m2 = 2049;
    std::cout << "t5 = "; t5.display(); std::cout << '\n';
}
#include "T.h"
#include <iostream>

void test_T();

int main() {
    std::cout << "test Class T: \n";
    test_T();

    std::cout << "\ntest friend func: \n";
    func();
}

void test_T() {
    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 = "; t1.display(); cout << endl;

    T t2(3, 4);
    cout << "t2 = "; t2.display(); cout << endl;

    T t3(t2);
    t3.adjust(2);
    cout << "t3 = "; t3.display(); cout << endl;

    T t4(std::move(t2));
    cout << "t4 = "; t4.display(); cout << endl;

    cout << "test: T objects'current count: " << T::get_cnt() << endl;
}

截图 2025-10-22 08-04-21

  • 问题
    • 不能:截图 2025-10-22 08-07-33

    • 普通构造函数在手动创建对象并初始化的时候使用,复制构造函数在通过已有对象创建对象的时候使用,移动构造函数在使用move语义的时候使用,析构函数根据RAII在对象生命周期结束的时候自动调用

    • 截图 2025-10-25 14-39-31

      静态变量只能在一个.cpp文件中定义一次,如果在头文件中对静态变量进行初始化,被包含时每个.cpp文件都会生成自己的静态变量定义,链接器发现同名变量出现多次从而报重定义链接错误

实验任务2

  • 源码与运行测试截图
#include <string>
class Complex
{
private:
    double real;
    double imag;

    friend void output(const Complex &x);
    friend double abs(const Complex &x);
    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);
public:
    static const std::string doc;
    Complex(double real = 0.0, double imag = 0.0);
    Complex(const Complex &x);
    Complex(Complex &&x);
    Complex &operator=(const Complex &) = default;
    ~Complex();

    void add(const Complex &x) {
        real += x.get_real();
        imag += x.get_imag();
    }

    double get_real() const {
        return real;
    }

    double get_imag() const {
        return imag;
    }
};

void output(const Complex &x);
double abs(const Complex &x);
Complex add(const Complex &a, const Complex &b);
bool is_equal(const Complex &a, const Complex &b);
bool is_not_equal(const Complex &a, const Complex &b);


#include "complex.h"
#include <iostream>
#include <cmath>

const std::string Complex::doc{"a simple complex class"};

Complex::Complex(double r, double i): real{r}, imag{i} {
    std::cout << "comstructor called." << std::endl;
}

Complex::Complex(const Complex &x): real{x.real}, imag{x.imag} {
    std::cout << "compy comstructor called." << std::endl;
}

Complex::Complex(Complex &&x): real{x.real}, imag{x.imag} {
    std::cout << "move constructor called." << std::endl;
}

Complex::~Complex() {
    std::cout << "destructor called." << std::endl;
}

void output(const Complex &x)
{
    std::cout << x.real;
    if (x.imag >= 0) std::cout << " + ";
    else std::cout << " - ";
    std::cout << abs(x.imag) << "i";
}

double abs(const Complex &x)
{
    return sqrt(x.get_real() * x.get_real() + x.get_imag() * x.get_imag());
}

Complex add(const Complex &a, const Complex &b)
{
    return Complex(a.get_real() + b.get_real(), a.get_imag() + b.get_imag());
}

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

bool is_not_equal(const Complex &a, const Complex &b)
{
    return a.get_real() != b.get_real() || a.get_imag() != b.get_imag();
}


// ������ͷ�ļ�
// xxx
#include "complex.h"
#include <iostream>
#include <iomanip>
#include <complex>

void test_Complex();
void test_std_complex();

int main() {
    std::cout << "*******����1: �Զ�����Complex*******\n";
    test_Complex();

    std::cout << "\n*******����2: ��׼��ģ����complex*******\n";
    test_std_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);

    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.real = " << c5.get_real() 
         << ", c5.imag = " << c5.get_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;
}

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;
    const std::complex<double> c5(3.5);

    cout << "c1 = " << c1 << endl;
    cout << "c2 = " << c2 << endl;
    cout << "c3 = " << c3 << endl;
    cout << "c4 = " << c4 << endl;

    cout << "c5.real = " << c5.real() 
         << ", c5.imag = " << c5.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;
}

image

  • 问题
    • 右边更加简洁,更符合cpp的语法,运算其实是通过操作符函数来进行的,标准库在类中重载了操作符函数,从而达到这个效果
      • 其实不用,因为已经在complex中提供了访问这两个数据的安全接口,所以更应该通过接口对私有数据进行访问,这样更加安全
      • std::complex并没有将abs作为自己的友元
      • 类友元发生在两个类的实现紧密耦合的时候;操作符重载时可能也要,就是类外逻辑

实验任务3

  • 源码与运行测试截图
#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 <iostream>
#include <algorithm>

int PlayerControl::total_cnt = 0;

PlayerControl::PlayerControl() {}

// ������
// 1. �������ַ���תΪСд��ʵ�ִ�Сд������
// 2. ƥ��"play"/"pause"/"next"/"prev"/"stop"�����ض�Ӧö��
// 3. δƥ����ַ�������ControlType::Unknown
// 4. ÿ�γɹ�����parseʱ����total_cnt
ControlType PlayerControl::parse(const std::string &control_str)
{
    std::string s = control_str;
    std::transform(s.begin(), s.end(), s.begin(), ::tolower);

    if (s == "play")
    {
        ++total_cnt;
        return ControlType::Play;
    }
    else if (s == "pause")
    {
        ++total_cnt;
        return ControlType::Pause;
    }
    else if (s == "next")
    {
        ++total_cnt;
        return ControlType::Next;
    }
    else if (s == "prev")
    {
        ++total_cnt;
        return ControlType::Prev;
    }
    else if (s == "stop")
    {
        ++total_cnt;
        return ControlType::Stop;
    }

    return ControlType::Unknown;
}

void PlayerControl::execute(ControlType cmd) const
{
    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 "PlayerControl.h"
#include <iostream>

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

截图 2025-10-25 14-59-29
截图 2025-10-25 15-00-41

实验任务4

  • 源码与运行测试截图
#ifndef FRACTION_H
#define FRACTION_H

#include <iostream>
#include <string>

class Fraction {
private:
    int up; 
    int down;  

    void simplify();

public:
    static const std::string doc;

    Fraction(int numerator = 0, int denominator = 1);
    Fraction(const Fraction& other);

    int get_up() const;
    int get_down() const;

    Fraction negative() const;
};

namespace fracutil {
    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);
}

using fracutil::output;
using fracutil::add;
using fracutil::sub;
using fracutil::mul;
using fracutil::div;

#endif


#include "Fraction.h"
#include <numeric>
#include <stdexcept>

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

Fraction::Fraction(int numerator, int denominator)
    : up(numerator), down(denominator) {
    if (down == 0) {
        throw std::invalid_argument("分母不能为0");
    }
    if (down < 0) {
        up = -up;
        down = -down;
    }
    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 Fraction::simplify() {
    int g = std::gcd(up, down);
    if (g != 0) {
        up /= g;
        down /= g;
    }
}

namespace fracutil {

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

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

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

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

Fraction div(const Fraction& a, const Fraction& b) {
    if (b.get_up() == 0) {
        throw std::invalid_argument("除数分数的分子为0,不能相除");	// 改成直接抛异常了
    }
    int numerator = a.get_up() * b.get_down();
    int denominator = a.get_down() * b.get_up();
    return Fraction(numerator, denominator);
}

}
#include "Fraction.h"
#include <iostream>

void test1();
void test2();

int main() {
    std::cout << "����1: Fraction��������ܲ���\n";
    test1();

    std::cout << "\n����2: ��ĸΪ0����: \n";
    test2();
}

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

截图 2025-10-25 15-01-45

  • 问题
    • 如果要用运算符的话就用友元函数,如果要模块化就命名空间+自由函数
    • 友元函数会破坏封装,滥用会导致类与函数的耦合度上升

五、实验结论

实验任务1

  1. 关于友元函数 func
    • 如果在 T.h 中去掉 friend void func(); 的声明,程序无法通过编译。
    • 原因:func 需要访问 T 的私有成员 m2,没有友元声明时无法访问私有数据,会导致编译报错。
  2. 构造函数与析构函数
    • 普通构造函数:用于对象创建时的初始化。
    • 复制构造函数:用于通过已有对象创建新对象时调用。
    • 移动构造函数:用于使用 std::move 或右值生成对象时调用,减少不必要的拷贝。
    • 析构函数:对象生命周期结束时自动调用,用于资源释放(RAII)。
  3. 静态成员与链接问题
    • 静态成员变量只能在一个 .cpp 文件中定义一次。
    • 头文件中初始化静态成员会导致被多次包含,从而出现 multiple definition 链接错误。
    • 正确做法:在 .h 中声明,在 .cpp 中定义。

实验任务2

  1. 自定义类 Complex 与标准库 std::complex 对比

    • 标准库 std::complex 的语法更简洁,自然支持运算符重载。
    • 函数和运算内部有关联,标准库通过重载操作符实现。
  2. 关于友元函数

    • 自定义类中 output/abs/add 等函数并不一定需要访问私有数据,可以通过公共接口实现,但使用友元可简化代码。
    • std::complex 并未将 abs 设为友元,而是提供了公共访问接口。
    • 使用友元函数的时机:当函数实现需要访问类的私有成员,且该函数逻辑属于类相关操作时。
  3. 禁止 = 拷贝构造

    • 如果构造对象时禁用 Complex c4 = c2; 的形式,可通过删除拷贝构造函数或赋值运算符:

      Complex(const Complex&) = delete;
      Complex& operator=(const Complex&) = delete;
      

实验任务3

  1. PlayerControl 功能
    • 利用枚举 ControlType 管理播放控制命令。
    • parse 函数将字符串映射为 ControlType 并计数。
    • execute 函数根据命令执行输出操作。

实验任务4

  1. 分数运算设计方案
    • 选择 命名空间 + 自由函数 方案:
      • 保持封装性,不破坏类私有成员。
      • 适合模块化设计,便于扩展。
    • 友元函数方案在需要运算符重载或直接访问私有数据时可使用,但滥用会增加耦合。
    • 静态成员函数方案适用于工具类函数,不适合自然表达算术运算符语义。
  2. 总结
    • 对于小型数值类(如 Fraction、Complex),友元函数可提高代码简洁性与表达性。
    • 对于库或模块化设计,推荐使用命名空间+自由函数,保持封装和可扩展性。

六、实验总结

  • 深入了解了不同场景下对于类的不同功能的实现方案的取舍方式
  • 复习了一些类设计的细节
  • 题外话
    • 关于多文件,直接提供参数编译了,正常情况下应该使用cmake或者直接使用makefile
    • 关于输出乱码,结论是gbk文件的压缩包在解压的时候需要提供参数帮助unar进行解压,否则会损失信息(诸如7z和unzip这类的解压工具不具备这种能力)
      解压出来的文件在编辑器中打开时也要设置解码格式为gbk。但考虑到只影响注释和output format就不处理了

参考资料

cppreference, chatgpt

posted @ 2025-10-25 15:37  witlethe  阅读(1)  评论(0)    收藏  举报