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

1

问题1:普通构造函数T(int x = 0, int y = 0):创建对象时给 m1、m2 赋初值,用参数新建对象时调用。t1没传参数,是默认值(0, 0),t2(3, 4)传了两个参数,都是用普通构造函数。

复制构造函数T(const T &t):拿一个已经存在的相同类的对象,复制出一个新对象,成员值跟被复制的一样,用同类对象去初始化新对象时调用。t3(t2)是用t2初始化t3,用复制构造函数。

移动构造函数T(T &&t):把一个对象的数据直接搬过来,不用复制,用std::move去初始化新对象时调用。t4(std::move(t2))是把,t2的值直接搬给t4,用移动构造函数。

析构函数~T():对象离开它所在的作用域、被销毁时自动调用一次。t1~t4在test()函数结束时依次被析构。

问题2:

2

不能正确编译。line8-10是 static 成员的类外定义和初始化。static成员是整个类共享的,必须在类外定义,如果放到头文件里,每个包含这个头文件的 .cpp都会各自定义一份,就会报重复定义的错误。

问题3:t1-t4 都是在test()函数里面定义的,所以作用域是test()函数体,从定义处开始到test()结束。在类外面不能通过t1直接访问私有成员m1、m2,私有成员只能被类自己的成员函数使用。这体现了类的封装性:把数据封装在类里,对外只暴露必要的入口。

问题4:3

throw的功能是抛异常:程序如果跑到这里发现出了问题,就抛 一个std::runtime_error出去,正常流程中断,顺着调用栈往上找能处理它的地方;如果一直没有可以接住的,程序就终止。程序会异常退出。已经创建好的对象会被正常销毁。因为异常往上抛的过程中网往上调用,在退出这些对象所在作用域时,已经构造好的局部对象的析构函数会被自动调用。

2.实验任务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 &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_;
};

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 &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) {
    std::cout << c.real_;
    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 &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();
}

4

问题1:① 必须给成员函数加上const,写成const成员函数。因为c6是const对象,const对象只能调用const成员函数。

5

② 不能。c6是const对象,初始化之后就不允许再修改,而但add()会修改对象自己的实部虚部,是非const成员函数,const对象不能调用它,编译器会报错。这体现了类中const的只读保护机制。

问题2:标准库写法更简洁,自定义类需要多次调用add()、is_equal()、output()函数。运算符本质上就是函数,只是给函数换了个更简洁的写法。

问题3:① 不是必须的,把它们写成普通非成员函数也能实现相同的功能。在类里对外暴露get_real()、get_imag()的接口,函数通过这些接口拿到实部虚部来运算。

② 不是友元。std::complex的abs是普通非成员函数,它通过real()、imag()这些接口取得实部虚部再算模长。参考页面:https://en.cppreference.com/w/cpp/numeric/complex/abs。

③ 当某个函数需要多次访问类内部几个成员,写成成员函数或用公开接口不方便时,才考虑友元,不然一般情况下尽量少用友元,因为我认为友元会把类的私有数据暴露给外部,破坏类的封装性。

3.实验任务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() {}

// 待补足
ControlType PlayerControl::parse(const std::string &control_str) {
    // 1. 先把输入字符串统一转成小写,实现大小写不敏感
    std::string s = control_str;
    for (char &ch : s)
        ch = static_cast<char>(std::tolower(static_cast<unsigned char>(ch)));
 
    // 2. 匹配"play"/"pause"/"next"/"prev"/"stop"并返回对应枚举;
    //    未匹配的字符串返回ControlType::Unknown
    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自增 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();
}

6

问题:因为total_cnt是static静态成员,属于整个类,不属于具体对象。const成员函数约束的是不能修改对象自己的普通成员,但静态成员属于类,所以不受const限制。

4.实验任务4

Fraction.h:

#pragma once
#include <string>
 
class Fraction {
public:
    static const std::string doc;
 
    Fraction(int up = 0, int down = 1);
    Fraction(const Fraction &other);
 
    int get_up() const;
    int get_down() const;
    Fraction negative() const;
 
private:
    int up_;
    int down_;
    void normalize();
};
 
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);

Fraction.cpp:

#include "Fraction.h"
 
#include <cstdlib>
#include <iostream>
#include <stdexcept>
 
const std::string Fraction::doc{
    "Fraction类 v 0.01 版.\n目前仅支持分数对象的构造、输出、加/减/乘/除运算."};
    
static int gcd_int(int a, int b) {
    a = std::abs(a);
    b = std::abs(b);
    while (b != 0) {
        int t = a % b;
        a = b;
        b = t;
    }
    return a;
}
 
Fraction::Fraction(int up, int down) : up_{up}, down_{down} {
    if (down_ == 0)
        throw std::invalid_argument("Fraction: 分母不能为0");
    normalize();
}
 
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::normalize() {
    if (down_ < 0) {
        up_ = -up_;
        down_ = -down_;
    }
    if (up_ == 0) {
        down_ = 1;
        return;
    }
    int g = gcd_int(up_, down_);
    up_ /= g;
    down_ /= g;
}
 
void output(const Fraction &f) {
    if (f.get_down() == 1)
        std::cout << f.get_up();
    else
        std::cout << f.get_up() << "/" << f.get_down();
}
 
Fraction add(const Fraction &a, const Fraction &b) {
    return Fraction(a.get_up() * b.get_down() + b.get_up() * a.get_down(),
                    a.get_down() * b.get_down());
}
 
Fraction sub(const Fraction &a, const Fraction &b) {
    return Fraction(a.get_up() * b.get_down() - b.get_up() * a.get_down(),
                    a.get_down() * b.get_down());
}
 
Fraction mul(const Fraction &a, const Fraction &b) {
    return Fraction(a.get_up() * b.get_up(), a.get_down() * b.get_down());
}
 
Fraction div(const Fraction &a, const Fraction &b) {
    if (b.get_up() == 0)
        throw std::invalid_argument("Fraction: 分母不能为0");
    return Fraction(a.get_up() * b.get_down(), a.get_down() * b.get_up());
}

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

7

问题:我选的是方案2:分数类+命名空间自由函数。分数的加减乘除只需要分子分母算,类里已经有get_up()、get_down()公共接口,自由函数通过这两个接口就能完成计算,不需要把每个运算函数都加成友元。保存了类的封装性,不暴露私有数据,也方便增加新的运算。

五、实验总结

这次实验要把数据和操作数据的函数打包到一个类里,一开始还有点搞不明白,做完四个实验任务之后,我搞清楚了构造、复制构造、移动构造、析构的功能和分别在什么时候被调用,也明白了private私有成员只能通过公有接口或者友元访问,体现了类的封装性。同时,我还记住了static成员是整个类共享的,要在类外面初始化;const对象只能调const成员函数。写复数类、分数类的时候,我体会到要先想清楚“这个类需要有哪些数据、对外提供哪些操作”,再动手写。

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