看来如果类比较复杂,自己写copying fun还是比较麻烦的事情:
#include <iostream> #include<string> using namespace std; class Widget { public: Widget(int aData):m_Data(aData) { } virtual void Swap(Widget &aRhs) { int lTemp = aRhs.m_Data; aRhs.SetData(m_Data); m_Data = lTemp; } Widget& operator=(const Widget &aRhs) { Widget lTemp(aRhs); Swap(lTemp); return *this; } virtual int GetData() const { return m_Data; } virtual void SetData(int aData) { m_Data = aData; } private: int m_Data; }; class Drived: public Widget { public: Drived(int aData):Widget(0),m_DriveData(aData) { } void Swap(Drived &aRhs) { Widget::Swap(aRhs); int lTemp = aRhs.m_DriveData; aRhs.SetData(m_DriveData); m_DriveData = lTemp; } Drived(const Drived &aDrived):Widget(aDrived),m_DriveData(aDrived.m_DriveData) { } Drived& operator=(const Drived &aRhs) { Drived lDrived(aRhs); Widget::operator=(lDrived); Swap(lDrived); return *this; } virtual int GetData() const { return m_DriveData; } virtual void SetData(int aData) { m_DriveData = aData; } private: int m_DriveData; }; int main() { Widget lTest1(10); Widget lTest2(-10); lTest2 = lTest1; cout << lTest2.GetData() << endl; Drived lDrived1(20); Drived lDrived2(-20); lDrived1 = lDrived2; cout << lDrived2.GetData() << endl; }