在 Visual C++ 中,我可以这样做:
template <class T>
class A{
protected:
T i;
};
template <class T>
class B : public A<T>{
T geti() {return i;}
};
如果我尝试用 g++ 编译它,我会得到一个错误。我必须这样做:
template <class T>
class B : public A<T>{
T geti() {return A<T>::i;}
};
难道我不应该在标准 C++ 中做前者吗?还是 gcc 配置错误导致出现错误?
最佳答案
这过去是允许的,但在 gcc 3.4 中发生了变化.
在模板定义中,非限定名称将不再查找依赖基的成员(如 C++ 标准中的 [temp.dep]/3 所指定)。例如,
template <typename T> struct B {
int m;
int n;
int f ();
int g ();
};
int n;
int g ();
template <typename T> struct C : B<T> {
void h ()
{
m = 0; // error
f (); // error
n = 0; // ::n is modified
g (); // ::g is called
}
};
您必须使名称依赖,例如通过在它们前面加上this->。这是 C::h 的更正定义,
template <typename T> void C<T>::h ()
{
this->m = 0;
this->f ();
this->n = 0
this->g ();
}
关于c++ - 从子类 : gcc vs msvc 访问 protected 成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/194492/