C++, template, compiler error [duplicate]

2019-08-22 01:34发布

Possible Duplicate:
Why doesn't a derived template class have access to a base template class' identifiers?

Translating of the following program

A.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

causes an error: "a was not declared in this scope". (Netbeans 6.9.1).

But the construction

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

is correct... Where is the problem?

Is it better to use forward declaration or file include directive?

B.h

template <class T>
class A;

vs.

#include "A.h"

1条回答
2楼-- · 2019-08-22 02:15

A<T>::a is a dependent name, so you can't use it unqualified.

Imagine that there was a specialization of A<int> somewhere:

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

What should the compiler do now? Or what if A<int>::a was a function instead of a variable?

Qualify your access to a, as you've already discovered this->a, and things will work right.

查看更多
登录 后发表回答