【问题标题】:C++ Inherited template classes don't have access to the base class [duplicate]C ++继承的模板类无权访问基类[重复]
【发布时间】: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


【解决方案1】:

您需要使用this-&gt;xthis-&gt;y 帮助编译器。

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

【讨论】:

    【解决方案2】:

    您必须明确引用父级:

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

    【讨论】:

      猜你喜欢
      • 2013-05-04
      • 1970-01-01
      • 2016-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-10
      相关资源
      最近更新 更多