zoukankan      html  css  js  c++  java
  • EffectiveC++ Item12

    看来如果类比较复杂,自己写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;
    }
    

      

  • 相关阅读:
    【JAVA与C#比较】其它
    C#和java之间的一些差异与共性
    C#与Java的语法差异
    关于npm本地安装模块包(node_modules),安装不了的问题
    vue
    vue
    vue
    vue
    v
    vue -model
  • 原文地址:https://www.cnblogs.com/xiangshancuizhu/p/2731759.html
Copyright © 2011-2022 走看看