C++子类的拷贝构造和拷贝赋值
子类拷贝构造函数
#include<iostream> class Base { public: Base(int i = 0) :m_i(i) { } Base(const Base& that) :m_i(that.m_i) { //基类拷贝构造 std::cout << "基类拷贝构造函数" << '\n'; } int m_i; }; class Derived :public Base { public: Derived(int i=0,int j=0):Base(i),m_j(j){} Derived(const Derived& that) :Base(that),m_j(that.m_j) { //子类拷贝构造函数 //Base(that) 执行基类拷贝构造函数 std::cout << "子类拷贝构造函数" << '\n'; } int m_j; }; int main() { Derived d(100, 200); Derived dd = d; //拷贝构造 std::cout << d.m_i << ", " << d.m_j << std::endl; std::cout << dd.m_i << ", " << dd.m_j << std::endl; return 0; }
如果子类没有定义拷贝构造函数,那么编译器会提供缺省的拷贝构造函数,该函数会自动调用基类的拷贝构造函数
子类拷贝赋值函数
#include<iostream> class Base { public: Base(int i = 0) :m_i(i) { } Base& operator=(const Base& that) { //基类拷贝赋值 std::cout << "基类拷贝赋值" << std::endl; if (&that != this) { //防止自赋值 m_i = that.m_i; } return *this; } int m_i; }; class Derived :public Base { public: Derived(int i=0,int j=0):Base(i),m_j(j){} Derived& operator=(const Derived& that) { //子类拷贝赋值 std::cout << "子类拷贝赋值" << std::endl; if (&that != this) { //防止自赋值 Base::operator=(that); //执行基类拷贝赋值函数 m_j = that.m_j; } return *this; } int m_j; }; int main() { Derived d(100, 200); Derived dd; dd = d; std::cout << dd.m_i << " " << dd.m_j << std::endl; return 0; }
如果子类没有定义拷贝赋值函数,那么编译器会提供缺省的拷贝赋值函数,该函数会自动调用基类的拷贝赋值函数