[C++ Daily] 确保类复制了所有应该复制的成员

确保类复制了所有应该复制的成员

image-20240909093304369

image-20240909093331287

image-20240909093344474

结果:

image-20240909093409415

源代码:

#include <iostream>
#include <string>
#include <vector>
/**
 * copy操作应该包含对象内的所有成员变量及所有父类的成员变量,
 * 此种可以通过调用对应的拷贝构造与拷贝赋值操作完成
 */

/// @brief simple terminal print
/// @param msg 
void log_w(const char* msg) {
    std::cout << msg << std::endl;
}
/// @brief 用户自定义类,包含拷贝构造与拷贝复制操作,操作对象成员为int基本内置类型
class Date {
    public:
    Date() = default;
    ~Date() = default;

    Date(const Date& rhs):day_(rhs.day_) {
        log_w("Date copy construct");
    }

    Date& operator=(const Date& rhs) {
        log_w("Date copy assignment function");
        this->day_ = rhs.day_;
        return *this;
    }

    private:
    int day_;
};

/// @brief 基类,包含拷贝构造与拷贝赋值函数,操作对象成员为std::string stl型str_与用户自定义型Date date_;
class Base {
    public:

    Base() = default;
    ~Base() = default;

    Base(const Base& rhs):str_(rhs.str_),date_(rhs.date_) {
        log_w("Base copy construct");
    }

    Base& operator=(const Base& rhs) {
        log_w("Base copy assignment function");
        str_ = rhs.str_;
        date_ = rhs.date_;
        return *this;
    }

    private:
    std::string str_;
    Date date_;
};

/// @brief 派生类(:Base),包含stl型std::vector及继承Base的private成员;
class Derived : public Base {
    public:
    Derived() = default;
    ~Derived() = default;
    //此处初始化组调用父类的拷贝构造函数进行构造
    Derived(const Derived& derived):vec_(derived.vec_),Base(derived) {
        log_w("Derived copy construct");
    }
    //此处赋值调用父类的拷贝赋值函数进行赋值
    Derived& operator= (const Derived& rhs) {
        log_w("Derived copy assignment function");
        Base::operator=(rhs);
        vec_ = rhs.vec_;
        return *this;
    }

    private:
    std::vector<int> vec_;
};

int main() {
    Date date_1;    //构造
    Date date_2(date_1);    //拷贝构造
    date_2 = date_1;    //拷贝赋值

    Base base_1;    //构造
    Base base_2(base_1);    //拷贝构造
    base_2 = base_1;    //拷贝赋值

    Derived d_1;    //构造
    Derived d_2(d_1);   //拷贝构造
    d_2 = d_1;  //拷贝赋值

    return 0;
}
posted @ 2024-09-09 09:42  Neko_Code  阅读(1)  评论(0编辑  收藏  举报