这是我需要做的事情:
#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变量不在范围内。这是我使用模板的方式的问题吗?
任何人都可以帮我解决这个问题吗?
THX
编辑:
我尝试使用this-&gt; v_b或B&lt; type&gt; :: v_b作为建议here并且正常工作!感谢您的帮助
答案 0 :(得分:3)
在表达式中:
cout << "v_b = " << v_b << endl;
v_b
是一个非依赖表达式(即它不像看起来它依赖于模板参数。对于非依赖表达式,第一阶段查找必须解析符号,它只会通过查看非依赖的上下文来实现。这不包括模板化的基础(因为它取决于类型参数)。简单的解决方法是使用this
限定调用:
cout << "v_b = " << this->v_b << endl;
现在它是依赖表达式(this
,它明显取决于实例化类型),并且查找被延迟到第二阶段,其中类型被替换并且可以检查基数