我有一個final
函數的問題。我想「停止」類中的多態性,但我仍然想在派生類中生成相同的函數。是否有可能繼承最終功能但創建相同功能(不覆蓋)的派生類?
事情是這樣的:
class Base{
protected:
int _x, _y;
public:
Base(int x = 0, int y = 0) : _x(x), _y(y){};
int x() const { return _x; }
int y() const { return _y; }
virtual void print()const{ cout << _x*_y << endl; }
};
class Derived : public Base{
public:
Derived(int x = 0, int y = 0) : Base(x, y){}
void print()const final { cout << _x*_y/2.0 << endl; } // final inheritance
};
class NonFinal : public Derived{
void print()const{ cout << "apparently im not the last..." << endl }
// here i want a new function. not overriding the final function from Derived class
};
作爲一般規則,我會調用隱藏繼承成員的代碼上的設計錯誤(顯而易見的例外是覆蓋繼承的虛函數)。我會建議在'NonFinal'中調用其他方法。如果你發現自己需要這樣做,那麼關於你的OO設計的東西就不好。 – cdhowie