开发者

Inheritance and templates and virtual functions ( this can get messy)

Just finding my way around templates so was trying out a few stuff.

Let me know what I am doing wrong here.

I am trying to overload a inherited templates virtual method.

// 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;
}

`

This gives the error :

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: candidat开发者_开发百科es are: next<double, float>::next()
function.cpp:25: note:                 next<double, float>::next(const next<double, float>&)

If this isnt the right way to proceed, some info on template inheritance would be great


The next class does not automatically inherit the constructors from its parent class. You have to define any constructors explicitly. This applies to all derived classes, whether template and virtual functions are involved or not.

If you want to define a constructor from next that takes two Ts and forwards them to the corresponding mypair constructor, you would do it like this:

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

Again, this is generally applicable even without templates involved.


Full Solution if anyone is interested ( thanks to Tyler)

// 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜