为什么派生类在模板化时没有权限访问其 protected 基类成员?
class MyBase {
protected:
int foo;
};
template<typename Impl>
class Derived : public Impl {
public:
int getfoo() {
return static_cast<Impl*>(this)->foo;
}
};
编译器提示 foo 受到保护。为什么?
error: int MyBase::foo is protected
最佳答案
您正在访问 foo
通过 MyBase*
而不是 Derived<MyBase>*
.您只能通过您自己的类型访问 protected 成员,而不能通过基类型访问。
试试这个:
int getfoo() {
return this->foo;
}
来自 C++ 2003 标准,11.5/1 [class.protected]
:“当派生类的友元或成员函数引用 protected 非静态成员函数或
基类的 protected 非静态数据成员……访问必须通过
派生类本身(或从该类派生的任何类)的指针、引用或对象”
关于C++ 模板参数作为基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10095542/