C++模板类的派生类中访问基类成员必须显式调用(作用域限定)

一个常见的派生类访问基类成员变量的例子:

template<int dim>

class A{
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

猜你喜欢

转载自blog.csdn.net/qq_41230365/article/details/79312017