【发布时间】:2011-01-26 21:32:04
【问题描述】:
我是第一次使用模板类,并试图弄清楚为什么编译器在我使用继承时似乎不喜欢。
代码如下:
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; };
};
编译器输出:
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
这样用模板不行吗?
谢谢
【问题讨论】:
-
考虑在类构造函数中使用初始化器而不是赋值。
-
在这种特殊情况下,您也可以调用基类 ctor,因为它的作用相同。
-
@Christoph:更准确地说,无论您是否编写这样的调用,您总是调用基类ctor。所以在这段代码中,
xVector2()中的赋值是多余的——它们已经被基本构造函数设置为零。
标签: c++ templates inheritance