问题
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