C ++,模板,编译错误 [英] C++, template, compiler error

查看:246
本文介绍了C ++,模板,编译错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

为什么派生模板类不能访问基本模板类的标识符?

翻译以下程序

Ah

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

Bh

#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

会导致错误:未在此范围中声明。 (Netbeans 6.9.1)。

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

但建设

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

是问题吗?

使用前进声明或文件include指令更好吗?

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

Bh

template <class T>
class A;

vs。

#include "A.h"


推荐答案

code> A< T> :: a 是一个依赖名称,因此您不能使用它不合格。

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

A< int> 的特殊地方:

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

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

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

a ,因为你已经发现 this-> a ,事情会正常工作。

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

这篇关于C ++,模板,编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆