2017-06-22 85 views
5

我有一個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 
}; 
+2

作爲一般規則,我會調用隱藏繼承成員的代碼上的設計錯誤(顯而易見的例外是覆蓋繼承的虛函數)。我會建議在'NonFinal'中調用其他方法。如果你發現自己需要這樣做,那麼關於你的OO設計的東西就不好。 – cdhowie

回答

2

很抱歉,但它不可能在派生類中創建一個函數,當具有相同名稱的功能存在作爲基類final。你需要重新考慮你的設計。

問題源於這樣一個事實,即派生類中具有與基類中的函數相同名稱的函數聲明被視爲覆蓋override關鍵字是否存在的嘗試(由於歷史原因,I假設)。所以你不能「關閉」覆蓋。

這裏有一個相關的標準報價:

§10.3/4 class.virtual]

如果在某些類B一個虛函數f標有的virt-符final和從B派生的類D函數D::f覆蓋B::f,該程序是格式不正確的。 [示例:

struct B { 
    virtual void f() const final; 
}; 
struct D : B { 
    void f() const; // error: D::f attempts to override final B::f 
}; 

末端

2

我覺得這是一個實驗性的問題,因爲其實你應該反思一下,你在做什麼,當你需要爲「超越最後的功能」(聽起來矛盾,不是嗎?)。

但是,您可以引入一個「虛擬」參數,即void NonFinal::print(int test=0)const,它讓編譯器將成員函數視爲不同的參數。不知道這是否能解決你的「問題」;但至少它引入了一個具有相同名稱的函數,該函數仍然可以在不傳遞參數的情況下調用,並且與DerivedBase中的函數分開。

class NonFinal : public Derived{ 
public: 
    void print(int test=0)const{ cout << "apparently im not the last..." << endl; } 
}; 

int main() { 

    Base b (10,10); 
    Derived d (20,20); 
    NonFinal nf; 
    Base *bPtr = &d; 
    bPtr->print(); // gives 200 
    bPtr = &nf; // gives 0 
    bPtr->print(); 
    nf.print(); // gives "apparantly..." 
}