【发布时间】:2012-07-01 10:57:15
【问题描述】:
这是我需要做的:
#include <iostream>
using namespace std;
class A
{
public :
virtual void fa() = 0;
};
template <typename type>
class B : public A
{
protected :
int v_b;
};
template <typename type>
class C : public B<type>
{
public :
void fa()
{
// whatever action that try to access v_b
cout << "v_b = " << v_b << endl;
}
};
int main()
{
C<int> toto;
toto.fa();
return 0;
}
这里是 g++ 输出:
test.cpp: In member function ‘void C<type>::fa()’:
test.cpp:25:29: error: ‘v_b’ was not declared in this scope
据我了解,v_b 是 B 的受保护成员,因此可以在 C 中访问。A 和 B 都是抽象类,我需要在 C 类中重写 A 的 f_a() 方法才能实例化它。因为编译器告诉我这个
test.cpp: In member function ‘void C<type>::fa()’:
和不
‘void A::fa()’:
我不明白为什么 v_b 变量不在范围内。这是我使用模板方式的问题吗?
谁能帮我解决这个问题?
谢谢
编辑:
我尝试按照here 的建议使用 this->v_b 或 B
【问题讨论】:
-
this->v_b将修复代码。 @CharlesBailey 的链接解释了原因。 -
您使用的是旧版本的 g++ 吗? ideone.com/fBXNK
-
gcc 版本 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5)错误)谢谢链接
标签: c++ templates inheritance scope overriding