C++ Inherited template classes don't have access to the base class [duplicate]

六月ゝ 毕业季﹏ 提交于 2019-12-29 08:18:15

问题


I am working with template classes for the first time, and trying to figure out why the compiler doesn't seem to like when I use inheritence.

Here is the code:

template <typename T>
struct xPoint2
{
    T x;
    T y;

    xPoint2() { x = 0; y = 0; };
};

template <typename T>
struct xVector2 : xPoint2<T>
{
    xVector2() { x = 0; y = 0; };
};

The compiler output:

vector2.hh: In constructor ‘xVector2<T>::xVector2()’:
vector2.hh:11: error: ‘x’ was not declared in this scope
vector2.hh:11: error: ‘y’ was not declared in this scope

Is it not possible to use templates in this way?

Thanks


回答1:


You need to help the compiler out by using this->x and this->y.

http://www.parashift.com/c++-faq/templates.html#faq-35.19




回答2:


You must explicitly refer to parent:

template <typename T>
struct xVector2 : xPoint2<T>
{
    typedef xPoint2<T> B;
    xVector2() { B::x = 0; B::y = 0; };
};


来源:https://stackoverflow.com/questions/4810272/c-inherited-template-classes-dont-have-access-to-the-base-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!