【问题标题】:C++, template, compiler error [duplicate]C ++,模板,编译器错误[重复]
【发布时间】:2010-12-27 16:26:36
【问题描述】:

可能重复:
Why doesn't a derived template class have access to a base template class' identifiers?

以下程序的翻译

啊.h

#ifndef A_H
#define A_H
template <class T>
class A
{
  protected :
    T a;
  public:
    A(): a(0) {}
};
#endif

B.h

#ifndef B_H
#define B_H
template <class T>
class A;

template <class T>
class B: public A <T>
{
  protected:
    T b;

  public:
    B() : A<T>(), b(0) {}
    void test () { b = 2 * a;}   //a was not declared in this scope
};
#endif

导致错误:“a 未在此范围内声明”。 (Netbeans 6.9.1)。

但是建设

void test () { b = 2 * this->a;} 

是正确的...问题出在哪里?

使用前向声明或文件包含指令更好吗?

B.h

template <class T>
class A;

对比

#include "A.h"

【问题讨论】:

标签: c++ templates compilation


【解决方案1】:

A&lt;T&gt;::a 是一个依赖名,所以不能无条件使用。

想象一下在某处有一个A&lt;int&gt; 的特化:

template<> class A<int> { /* no a defined */ };

编译器现在应该做什么?或者如果A&lt;int&gt;::a 是一个函数而不是一个变量呢?

确认您对a 的访问权限,因为您已经发现了this-&gt;a,一切都会正常进行。

【讨论】:

  • 哦,我多么喜欢在没有任何解释的情况下被否决:(
  • 你的答案是正确的。赞成制衡。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-28
  • 1970-01-01
相关资源
最近更新 更多