2012-02-03 76 views
0
template <class T, class U, class Child> 
class Parent { 
public: 
    virtual T blah() { 
    return gaga; 
    } 
protected: 
    T gaga; 
}; 

class Child : public Parent<double, double, Child> { 
    virtual void blah(int overloaded) { 
    } 

    virtual void func() { 
    blah(); 
    } 
}; 

int main() { 
    Child* p = new Child(); 
} 

爲什麼上面的代碼不能編譯?爲什麼我不能像這樣重載我的虛擬功能?虛擬模板功能過載

我得到的錯誤:

prog.cpp: In member function ‘virtual void Child::func()’: 
prog.cpp:16: error: no matching function for call to ‘Child::blah()’ 
prog.cpp:12: note: candidates are: virtual void Child::blah(int) 
prog.cpp: In function ‘int main()’: 
prog.cpp:21: warning: unused variable ‘p’ 

回答

4

的方法void blah(int)Child隱藏在Parent繼承T blah(),您可以通過添加行

using Parent::blah; 

Child取消隱藏它。如果您想要訪問Parent::blah(),您必須確保using聲明處於公開訪問部分。所以,你將不得不

public: 
    using Parent::blah; 
private: 
    ... 

增加的Child頂部,使Parent::blah()看到的一切。您也可以使用Parent::blah()明確引用基類方法,而不是僅指blah()。更多信息可在here

+0

謝謝。這解決了問題,我可以在課堂上使用它......但是,我不能使用Parent :: blah()以外的內容。例如:p-> blah(); – user988098 2012-02-03 20:39:38

+1

爲此,您必須將'using'語句放在公共範圍內。我已經更新了我的答案。 – 2012-02-03 21:20:07

-1

你只是有不同的原型blah在孩子。對於父級,它是T blah(),子級是void blah(int),而它應該是double blah()以產生正確的虛擬函數重載。

另外,你有什麼在父親子模板參數?