C++, template, compiler error [duplicate]

痴心易碎 提交于 2019-12-11 23:30:41

问题


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:


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.



来源:https://stackoverflow.com/questions/4540106/c-template-compiler-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!