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() { ... }
}
其實,DerivedA
和DerivedB
類沒有額外數據成員,他們唯一的目的是從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.對不起我的英語。
如果您的代碼按照需要工作,但您只希望對最佳做法或完成相同任務的替代方法進行檢查,可以將其遷移到Stack Exchanges Code Review部分。 – YoungJohn
如果某人交換()兩個不同類型的派生類實例會怎樣?或者是對一個Basic和一個DerivedA的引用?似乎爲基類定義的swap()是充滿的。 –
實際上,編程子網站更適合更高級別的設計問題。這顯然不是一個代碼審查問題。 – lpapp