2010-08-31 43 views
4

只是找到我的方式周圍的模板,所以嘗試了一些東西。繼承和模板和虛函數(這可能會變得混亂)

讓我知道我在做什麼錯在這裏。

我想重載一個繼承的模板虛擬方法。

// class templates 
#include <iostream> 
using namespace std; 

template <class T, class A> 
class mypair { 
    T a, b; 
    public: 
    mypair (T first, T second) 
     {a=first; b=second;} 
    virtual A getmax(); 
}; 

template <class T, class A> 
A mypair< T, A>::getmax() 
{ 
    A retval; 
    retval = a>b? a : b; 
    return retval; 
} 



template <class T, class A> 
class next : public mypair <T, A> { 
     A getmax() 
     { 
     cout <<" WHOO HOO"; 
     } 
}; 


int main() { 
    mypair <double,float> myobject(100.25, 75.77); 
    next<double,float> newobject(100.25, 75.77); 
    cout << myobject.getmax(); 
    return 0; 
} 

`

這給了錯誤:

function.cpp: In function ‘int main()’: 
function.cpp:35: error: no matching function for call to ‘next<double, float>::next(double, double)’ 
function.cpp:25: note: candidates are: next<double, float>::next() 
function.cpp:25: note:     next<double, float>::next(const next<double, float>&) 

如果這個心不是正確的前進方式,對模板繼承的一些信息將是巨大的

回答

7

next類不從其父類自動繼承構造函數。你必須明確定義任何構造函數。這適用於所有派生類,無論是否涉及模板函數和虛函數。

如果你想從next採用兩個T S和它們轉發到相應的mypair構造函數定義構造函數,你會做這樣的:

next (T first, T second) 
    : mypair<T,A>(first, second) 
{ 
} 

同樣,這甚至是普遍適用的,而不模板參與其中。

+0

首先感謝您的答覆。 所以如果我要爲下一個實例化一個對象(因爲它不是一個模板) 我該怎麼做? 我嘗試以下兩種方式 未來newobj(100.25,77.75)//我知道這是錯誤的,因爲模板不會是能夠找出數據類型是 未來<雙,浮法> newobj(100.25 ,77.75); //我得到一個錯誤,接下來不是一個模板..好吧 那我該怎麼做呢。 – Sii 2010-08-31 03:12:39

+0

'next newobj(100.25,77.75)'是做這件事的正確方法。一定還有其他的錯誤。你在「下一個」課中忘了「公衆:」了嗎?我不認爲你的意思是'next :: getmax'是一個私有方法。缺少這可能會導致其他問題。 – 2010-08-31 03:25:38

+0

我確實將getmax更改爲public.But使用第二種方法,編譯器接下來給出的錯誤不是模板,我想因爲下一個不是模板'next newobj(100.25,77.75)'將會是錯誤? (讓下一個人認爲是模板) – Sii 2010-08-31 03:35:58

3

完整的解決方案,如果有人有興趣(感謝泰勒)

// class templates 
#include <iostream> 
using namespace std; 

template <class T, class A> 
class mypair { 
     T a, b; 
    public: 
    mypair (T first, T second) 
     {a=first; b=second;} 
    virtual A getmax(); 
}; 

template <class T, class A> 
A mypair< T, A>::getmax() 
{ 
    A retval; 
    retval = a>b? a : b; 
    return retval; 
} 







template <class T, class A> 
class next: mypair<T,A> 
{ 
public: 

     next (T first, T second) : mypair<T,A>(first, second) 
     { 
     } 

     A getmax() 
     { 
     cout<<"WOO HOO"; 
     } 
}; 


int main() { 
    mypair <double,float> myobject(100.25, 75.77); 
    next<double,float> newobject(100.25, 75.77); 
    cout << newobject.getmax(); 
    return 0; 
} 
+0

+1:對它做得很好 – Chubsdad 2010-08-31 04:12:37