模板和继承问题

时间:2019-04-08 15:16:28

标签: c++ templates inheritance

我试图使我所有的类都通用,但是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()
            ^~~~~

1 个答案:

答案 0 :(得分:0)

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

../assets/dark.less

请注意,Point的构造函数的命名方式类似于 Circle() : Point<V>() { radius=0; }