确保类复制了所有应该复制的成员
结果:
源代码:
#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;
}