实验2 现代C++编程初体验

实验任务1

代码组织:

T.h:类T的声明、友元函数声明
T.cpp:类T的实现、友元函数实现
task1.cpp:测试模块、main函数

T.h

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

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';
    std::cout << "func: T objects'current count: " << T::get_cnt() << std::endl;
}

task1.cpp

#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 085124

问题1:不能正常运行,报错信息截图:

屏幕截图 2025-10-22 090121

原因:报错信息表明:func()函数在作用域中未定义。在T类中的友元声明表示func()不是T类的成员,因此func()缺少函数声明,无法通过编译。

问题2:(1)普通构造函数T(int x = 0, int y = 0)的功能是直接使用输入的具体数据初始化创建的类对象的数据变量,在没有初始化或使用具体数据初始化时调用。
(2)复制构造函数T(const T &t)的功能是使用类对象来初始化创建的新的类对象,在使用类对象初始化新的类对象或在函数间按值传递对象时调用。
(3)移动构造函数T(T &&t)的功能是将目标类对象的数据直接“移动”至创建的新类对象的数据变量中,在显式使用move()或编译器自动优化时调用,在函数传值时使用可以避免出现意外的对象拷贝,同时对于大型类必须的值传递可以加快速度,能近似达到传递引用的速度。

问题3:不能正常运行,报错信息截图:

屏幕截图 2025-10-22 094121

原因:类中静态数据成员初始化只能有且仅有一次,因此要在.cpp文件中初始化,头文件会被多个文件包含后编译,显然不符合只初始化一次的要求,尽管多次初始化结果时一样的。

实验任务2

代码组织:

Complex.h:类T的声明、友元函数声明
Complex.cpp:类T的实现、友元函数实现
task2.cpp:测试模块、main函数

Complex.h

#ifndef MY_COMPLEX_H_
#define MY_COMPLEX_H_

#include <string>

class Complex
{
    // 对象属性、方法
    private:
        double real, imag;
		
    public:
        Complex(double r = 0.0, double i = 0.0);	// 普通构造函数
        Complex(const Complex&);	// 复制构造函数
        Complex(const Complex&&) noexcept;	// 移动构造函数

        double get_real() const;	// 显示Complex类对象实部
        double get_imag() const;	// 显示Complex类对象虚部
        Complex& operator=(const Complex&);
        Complex& operator=(const Complex&&) noexcept;	// 重载=运算符
        void add(const Complex&);	// 将一个Complex类对象加到另一个Complex类对象上
    // 类属性、方法
    public:
        static const std::string doc;	// 用于类说明
		
    // 类Complex友元函数声明
    friend void output(const Complex&);	// 以a+bi的形式显示Complex类对象的信息
    friend double abs(const Complex&);	// 对Complex类对象取模
    friend Complex add(const Complex&, const Complex&);	// 实现两个Complex类对象相加,返回Complex类对象
    friend bool is_equal(const Complex&, const Complex&);	// 判断两个Complex类对象是否相等
    friend bool is_not_equal(const Complex&, const Complex&);	//	判断两个Complex类对象是否相等
};

void output(const Complex&);
double abs(const Complex&);
Complex add(const Complex&, const Complex&);
bool is_equal(const Complex&, const Complex&);
bool is_not_equal(const Complex&, const Complex&);
		
#endif

Complex.cpp

#include "Complex.h"

#include <iostream>
#include <utility>
#include <string>
#include <cmath>

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

Complex::Complex(double r, double i): real(r), imag(i)
{
	
}

Complex::Complex(const Complex &c): real(c.real), imag(c.imag)
{
	
}

Complex::Complex(const Complex &&c) noexcept : real(c.real), imag(c.imag)
{
	
}

Complex& Complex::operator=(const Complex &c)
{
    if (this != &c)
    {
        real = c.real;
        imag = c.imag;	
    }
    return *this;	
}

Complex& Complex::operator=(const Complex &&c) noexcept
{
    if (this != &c)
    {
        real = c.real;
        imag = c.imag;	
    }
    return *this;
}

double Complex::get_real() const
{
    return real;
}

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

void Complex::add(const Complex &c)
{
    real += c.real;
    imag += c.imag;
}

void output(const Complex &c)
{
    std::cout << c.get_real() 
    << (c.get_imag() < 0 ? " - " : " + ") 
    << std::abs(c.get_imag()) << 'i';
}
		
double abs(const Complex &c)
{
    return std::sqrt(c.get_real() * c.get_real() + c.get_imag() * c.get_imag());
}

Complex add(const Complex &c1, const Complex &c2)
{
    Complex c;
    c.add(c1);
    c.add(c2);
    return c;
}

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

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

task2.cpp

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

运行测试结果截图:

屏幕截图 2025-10-26 164818

屏幕截图 2025-10-26 164845

问题1:标准库提供的写法更加简洁,使得类对象在使用时更加贴合基本数据类型的编码方式.函数和运算本质上几乎是一致的,运算符本身是一个形如operatorXXX()的函数,通过像重载函数一样重载运算符可以实现标准库模板类的写法。
问题2-1:否,函数output()/abs()/add()不需要访问私有数据成员,完全可以使用已有的get_XXX()add()成员函数来完成操作而不直接访问数据成员。
问题2-2:标准库没有把abs()设为友元函数,而是提供了一种具体化abs(const complex<T>& z)来处理复数取模的问题,正如上一小问提到的,abs()完全不需要访问对象的私有数据成员,因此没必要设为友元函数。
问题2-3:除非有必要破坏类的封装性,例如将operator+()重载为复数与浮点数相加,为了满足交换律,将函数设为友元来解决形如f + z没有成员函数来实现的问题,否则不应该随意使用友元函数。
问题3:使用delete关键字显式指出禁用赋值运算符,同时所有返回对象的功能函数都需要提前传入一个空对象来在函数退出时接收函数原本应该返回的对象。

实验任务3

代码组织:

PlayerControl.h:播放控制类PlayerControl声明
PlayerControl.cpp:播放控制类PlayerControl实现
task3.cpp:测试模块 + main

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 <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 trans_result;
    for (auto &c : control_str)
        trans_result += std::tolower(c);
    ++total_cnt;
    if ("play" == trans_result)
        return ControlType::Play;
    else if ("next" == trans_result)
        return ControlType::Next;
    else if ("prev" == trans_result)
        return ControlType::Prev;
    else if ("stop" == trans_result)
        return ControlType::Stop;
    else if ("pause" == trans_result)
        return ControlType::Pause;
    else
        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;
}

task3.cpp

#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-26 181620

实验任务4

代码组织:

Fraction.h:类Fraction声明、其他声明
Fraction.cpp:类Fraction实现、其他实现
task4.cpp:测试代码、main()函数

Fraction.h

#ifndef FRACTION_H_
#define FRACTION_H_

#include <string>

namespace frac
{
    // 数学工具函数
    int gcd(int, int);	//求最大公因数,用于化简分数
    int lcm(int, int);	//求最小公倍数,用于分数加减
				
    class Fraction
    {
        // 对象属性 方法
        public:
            Fraction(int u = 0, int d = 1);	// 默认构造函数
            Fraction(Fraction&);	// 拷贝构造函数
            Fraction(Fraction&&) noexcept;	// 移动构造函数
			
            int get_up() const;	// 返回Fraction对象的分子
            int get_down() const;	// 返回Fraction对象的分母
            Fraction negative() const;	// 对Fraction对象取负
			
        private:
            int up, down;
			
            void simplify();	//对分数进行化简
		
        // 类属性 方法
        public:
            static const std::string doc;
			
    };
    // 工具函数
    void output(const Fraction&);	//以a/b形式输出一个分数
    Fraction add(const Fraction&, const Fraction&);	//实现两个分数相加
    Fraction sub(const Fraction&, const Fraction&);	//实现两个分数相减
    Fraction mul(const Fraction&, const Fraction&);	//实现两个分数相乘
    Fraction div(const Fraction&, const Fraction&);	//实现两个分数相除
	
}

#endif

Fraction.cpp

#include "Fraction.h"

#include <iostream>
#include <cmath>
#include <string>

namespace frac
{
    int gcd(int a, int b)
    {
        if (a * b == 0)
            return 0; 
        int temp;
        while (a % b)
        {
            temp = a % b;
            a = b;
            b = temp;
        }
        return b;
    }
	
    int lcm(int a, int b)
    {
        if (a * b == 0)
            return 0;
        return a * b / gcd(a, b);
    }
	
    const std::string Fraction::doc = "Fraction类 v 0.01版.\n目前仅支持分数对象的构造、输出、加/减/乘/除运算.";
	
    Fraction::Fraction(int u, int d): up(u), down(d)
    {
        simplify();
    }
	
    Fraction::Fraction(Fraction &f): up(f.up), down(f.down)
    {
		
    }
	
    Fraction::Fraction(Fraction &&f) noexcept: up(f.up), down(f.down)
    {
		
    }
	
    int Fraction::get_up() const
    {
        return up;
    }
	
    int Fraction::get_down() const
    {
        return down;
    }
	
    Fraction Fraction::negative() const
    {
        Fraction f;
        f.up = -up;
        f.down = down;
        return f;
    }
	
    void Fraction::simplify()
    {
        if (down < 0)
        {
            down *= -1;
            up *= -1;
        }
        int com_fac = gcd(std::abs(up), std::abs(down));
        if (com_fac != 1 && com_fac != 0)
        {
            up /= com_fac;
            down /= com_fac;
        }
    }
	
    void output(const Fraction &f)
    {
        if (f.get_down() == 0)
            std::cout << "分母不能为0";
        else if (f.get_down() == 1 || f.get_up() == 0)
            std::cout << f.get_up();
        else
            std::cout << f.get_up() << '/' << f.get_down();
    }
	
    Fraction add(const Fraction &f1, const Fraction &f2)
    {
        int com_den = lcm(f1.get_down(), f2.get_down());
        Fraction rf(com_den / f1.get_down() * f1.get_up() + com_den / f2.get_down() * f2.get_up(), com_den);
        return rf;
    }
	
    Fraction sub(const Fraction &f1, const Fraction &f2)
    {
        int com_den = lcm(f1.get_down(), f2.get_down());
        Fraction rf(com_den / f1.get_down() * f1.get_up() - com_den / f2.get_down() * f2.get_up(), com_den);
        return rf;
    }
	
    Fraction mul(const Fraction &f1, const Fraction &f2)
    {
        Fraction rf(f1.get_up() * f2.get_up(), f1.get_down() * f2.get_down());
        return rf;
    }
	
    Fraction div(const Fraction &f1, const Fraction &f2)
    {
        Fraction rf(f1.get_up() * f2.get_down(), f1.get_down() * f2.get_up());
        return rf;
    }
	
}

task4.cpp

#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 << frac::Fraction::doc << endl << endl;

    frac::Fraction f1(5);
    frac::Fraction f2(3, -4), f3(-18, 12);
    frac::Fraction f4(f3);
    cout << "f1 = "; frac::output(f1); cout << endl;
    cout << "f2 = "; frac::output(f2); cout << endl;
    cout << "f3 = "; frac::output(f3); cout << endl;
    cout << "f4 = "; frac::output(f4); cout << endl;

    const frac::Fraction f5(f4.negative());
    cout << "f5 = "; frac::output(f5); cout << endl;
    cout << "f5.get_up() = " << f5.get_up() 
        << ", f5.get_down() = " << f5.get_down() << endl;

    cout << "f1 + f2 = "; frac::output(frac::add(f1, f2)); cout << endl;
    cout << "f1 - f2 = "; frac::output(frac::sub(f1, f2)); cout << endl;
    cout << "f1 * f2 = "; frac::output(frac::mul(f1, f2)); cout << endl;
    cout << "f1 / f2 = "; frac::output(frac::div(f1, f2)); cout << endl;
    cout << "f4 + f5 = "; frac::output(frac::add(f4, f5)); cout << endl;    
}

void test2() {
    using std::cout;
    using std::endl;

    frac::Fraction f6(42, 55), f7(0, 3);
    cout << "f6 = "; frac::output(f6); cout << endl;
    cout << "f7 = "; frac::output(f7); cout << endl;
    cout << "f6 / f7 = "; frac::output(frac::div(f6, f7)); cout << endl;
}

运行测试结果截图:

屏幕截图 2025-10-27 203438

我在该场景中选择使用命名空间+自由函数的形式来实现分数的输出和计算,考虑到兼顾可扩展性,和可维护性,首先没有函数需要直接操作类对象的数据成员,为了保证封装性,尽量避免在没有必要的时候随意使用友元函数,其次,计算和输出函数本身与Fraction类没有强关联,考虑到可扩展性,也许会为其他的类实现具体化重载函数,因此不适合设为静态函数,同时静态函数的可维护性明显弱于自由函数,这些函数并不需要知道类中的数据组织方式,最后使用frac命名空间保证安全性,避免意外的同名函数误用。

实验总结:

C++中加入了新的工具:class,实现了C语言从原本面向过程编程到面向对象的转变,通过对象管理来组织更加复杂的代码,成员函数是对函数具体化的一种延申,不同的类可以有同名成员函数,尽管这些函数的实现可能完全不同,这是模板所做不到的,在调用时也不必考虑参数传递,对象的数据成员对于成员函数来说就是“全局变量”,在保证数据安全的同时又简化了编码过程。
类的封装性使得使用者能更加灵活自由的组织代码,由编译器来自动完成底层细节的操作,编译器对于类的处理有很多自动行为,例如构造函数,析构函数的隐式创建和调用,但这些自动行为可能造成最终的程序与目标实现效果不同,因此基于C++信任使用者的理念,允许用户重载这些函数。
但类的封装性也不是完全不可打破的————friend友元声明,仍旧秉承信任用户的理念,可以打破类的封装,使得外部函数可以访问类内的成员,提供了自由度和灵活性,但用户必须清楚自己在做什么,非必要时不应该随意使用。
在多文件编译时,要注意类本身创建了一个特殊的作用域,封装与完全信任的弊端是在头文件外部实现时如果不限定作用域可能定义一个新的同名函数,这种情况编译器不会报错,但会导致编译的文件链接失败。

posted @ 2025-10-27 22:15  bastille433  阅读(8)  评论(1)    收藏  举报