2010-08-31 54 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