2014-04-21 35 views
3

考慮以下代碼:繼承,沒有額外的數據成員

class Basic { 
public: 
    Basic() { ... } 
    Basic(const Basic& other) { ... } 
    virtual ~Basic() { ... } 

    virtual void foo() = 0; 
private: 
    int x, y, z; 
}; 

class DerivedA : public Basic { 
public: 
    DerivedA() : { ... } 
    virtual ~DerivedA() { ... } 

    virtual void foo() { ... } 
} 

class DerivedB : public Basic { 
public: 
    DerivedB() { ... } 
    virtual ~DerivedB() { ... } 

    virtual void foo() { ... } 
} 

其實,DerivedADerivedB類沒有額外數據成員,他們唯一的目的是從Basic類覆蓋純虛函數foo

我想要實現拷貝構造operator=兩個Derived類。

我的計劃是:

1)拷貝構造函數:

實現拷貝構造函數在派生類這樣的:

DerivedA(const DerivedA& other) : Basic(other) { 
    // Do nothing 
} 
DerivedB(const DerivedB& other) : Basic(other) { 
    // Do nothing 
} 

2)賦值運算符:

執行交換Basic類別:

void swap(Basic& other) { 
    std::swap(x, other.x); 
    std::swap(y, other.y); 
    std::swap(z, other.z); 
} 

重載運算符=的 '派生' 類:

DerivedA& operator=(const DerivedA& other) { 
    Derived tmp(other); 
    (*this).swap(tmp); 
    return (*this); 
} 

同爲DerivedB

現在我的問題:這是一個好的做法呢?我應該爲兩個派生類實現交換嗎?在這種繼承中有沒有更好的方法來實現這種方法?我的架構是否足夠好,能夠得到其他人的支持?

p.s.對不起我的英語。

+2

如果您的代碼按照需要工作,但您只希望對最佳做法或完成相同任務的替代方法進行檢查,可以將其遷移到Stack Exchanges Code Review部分。 – YoungJohn

+0

如果某人交換()兩個不同類型的派生類實例會怎樣?或者是對一個Basic和一個DerivedA的引用?似乎爲基類定義的swap()是充滿的。 –

+0

實際上,編程子網站更適合更高級別的設計問題。這顯然不是一個代碼審查問題。 – lpapp

回答

3

讓我提供一個備用的建議:使用默認的拷貝構造函數和拷貝賦值操作符,並讓編譯器爲您完成工作!你的類沒有任何淺層狀態,所以默認版本會按照你想要的來完成,而且編譯器正確地生成的可能性要比你不錯過複製粘貼的地方,引入一個微妙的錯誤。