一个常见的派生类访问基类成员变量的例子:
template<int dim>
public:
A():b(2){}
int b;
};
template<int dim>
class B:public A<dim>{
public:
B(){}
void f(){cout<<b<<endl;}
};
int main()
{
B<2> mb;
mb.f();
}
问题:这样编译会报错“ In member function 'void B<dim>::f()':
/usercode/file.cpp:15:17: error: 'b' was not declared in this scope
void f(){cout<<b<<endl;}”
如果加上限定符为cout<<A<dim>::b<<endl,则不会报错。或者把模板类改成普通类也可以在派生类中不加限定符地直接访问基类的成员。
这是为什么?见知乎:如何理解 模板类继承模板类, 子类看不到父类成员? - 知乎 https://www.zhihu.com/question/28139230