【问题标题】:Issue with template and inheritances模板和继承问题
【发布时间】:2019-04-08 15:16:28
【问题描述】:

我正在尝试使我的所有类都通用。但是问题出现在类 Circle 以及紧随其后的类中。我在哪里犯了错误?

当我将它们换成“int”时,它似乎起作用了。但这似乎无法满足我让类成为通用类的最初需求。

class DrawableObject
{
    public:
    virtual void print()=0;
};

template <typename T>
class Point : public DrawableObject
{

    T x;T y;

    public:
        Point()
        {   x=0;
            y=0;
        }
        Point(T a)
        {   x=a;
            y=a;
        }
        Point(T a,T b)
        {   x=a;
            y=b;
        }
        void setX(T newX)
        {   
            x=newX;
        }
        void setY(T newY)
        {   
            y=newY;
        }
        T getX()
        {   return x;
        }
        T getY()
        {   return y;}
        void print()
        {   cout<<"(X,Y) Coordinates are ("<<x<<","<<y<<")"<<endl;}
};

template <typename U>
class Rectangle : public Point<U>
{


    U width,height;

    public:
        Rectangle()
        {   width=0;
            height=0;
        }
        Rectangle(U a)
        {   width=a;
            height=a;
        }
        Rectangle(U a,U b)
        {   width=a;
            height=b;
        }       
        void setWidth(U newWidth)
        {   width=newWidth;}
        void setHeight(U newHeight)
        {   height=newHeight;}
        U getHeight()
        {   return height;}
        U getWidth()
        {   return width;}
        void print()
        {   cout<<"Rectangle is of area "<<width<<"X"<<height<<endl;}
};

问题从这里开始

template <typename V>
class Circle : public Point<V>
{

    V radius;

    public:
        Circle():Point()
        {   
            radius=0;
        }
        Circle(V a):Point(a)
        {   
            radius=a;
        }
        Circle(V a,V b,V c):Point(a,b)
        {   
            radius=c;
        }
        void setRadius(V newRadius)
            {radius=newRadius;}
        V getRadius()
            {return radius;}
        void print()
            {cout<<"Circle with centre at  ("<<getX()<<","<<getY()<<") and of radius "<<radius<<endl;}
};

错误如下所示。

oops_case_study.cpp: In constructor ‘Circle<V>::Circle()’:
oops_case_study.cpp:81:12: error: class ‘Circle<V>’ does not have any field named ‘Point’
   Circle():Point()
            ^~~~~

【问题讨论】:

  • 那是Point&lt;V&gt;
  • 您是否尝试过 Point,因为那是您继承的?我认为您还缺少 ~Point() 和 ~Circle()。
  • 不是你的直接问题,但请注意这种继承经常违反 LSP。矩形个点,圆形个点;说 Rectangle is a 点通常是错误的。类似地,一个不可变的 Square 是一个 Rectangle,但是一个可变的 Square 不是一个可变的 Rectangle(改变一个矩形的宽度的一个合理的后置条件是它的高度不变;对于一个正方形,这不会'不持有)。

标签: c++ templates inheritance


【解决方案1】:

当您从派生构造函数调用基类构造函数时,您还需要为基类指定模板参数,如下所示。

    Circle() : Point<V>()
    {   
        radius=0;
    }

注意,Point 的构造函数被称为 Point&lt;V&gt;()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多