【问题标题】:Templated polymorphism is not working [closed]模板化多态性不起作用[关闭]
【发布时间】:2013-05-26 16:30:40
【问题描述】:

我有 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();

}

【问题讨论】:

  • 您的代码甚至不应该编译。你能解决这个问题,并解释你遇到了什么问题吗?
  • 很好的基本问题是从基类的指针它没有像通常没有模板那样初始化派生类的对象它与模板有什么关系或者我在语法上有一些问题请忽略执行部分。这不是我现在关心的 ri8
  • 不知道,因为您发布的代码甚至无法编译。所以你正在运行不同的代码。我们怎么知道你没有显示的代码有什么问题?
  • 现在我已经在其中添加了一个可执行部分
  • 你能把它变成一个更短但完整的例子吗?这也应该是一种问答形式。您还没有提出问题,因此人们很难回答。

标签: c++


【解决方案1】:

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

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

【讨论】:

  • 谢谢它的工作
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 2021-06-23
    • 1970-01-01
    • 2011-10-14
    • 2014-07-01
    • 1970-01-01
    相关资源
    最近更新 更多