模板化多态性不起作用

时间:2013-05-26 07:31:24

标签: c++

我有3个类使用模板,2个来自抽象基类。在我的main()我正在应用多态概念,但是从指向基类的指针,派生类的对象没有被初始化。我不确定我的代码中的问题在哪里。

#include<iostream>
#include<conio.h>
using namespace std;

template<class T>
class polygon
{
protected:
    T a,b;
public:
    virtual T area()=0
}

template<class T>
class rectangle:public polygon
{

public:
    rectangle(T c,T d)
    {
        a=c;
        b=d;
    }
    T area()
    {
        return (a*b);
    }
};

template<class T>
class triangle:public polygon
{

public:
    rectangle(T c,T d)
    {
        a=c;
        b=d;
    }
    T area()
    {
        return (.5*a*b);
    }
};

template<class T>
class rectangle
{

public:
    rectangle(T c,T d)
    {
        a=c;
        b=d;
    }
    T area()
    {
        return (a*b);
    }
};
void main (void)
{

polygon<float>*ppoly=new rectangle<float>(4,5);
cout<<ppoly->area();
getche();

}

2 个答案:

答案 0 :(得分:0)

主要问题是你需要以这种方式继承模板类:

template<class T>
class rectangle : public polygon<T> // polygon is a template, you need to make
                                ^^^ // rectangle from a concrete polygon type

答案 1 :(得分:0)

另一件事:你有2个矩形类的定义。一个是继承自多边形,一个是继承自多边形。