为什么派生类Derived_from_Private不合法? 我注意到成员函数引用了 Base,但为什么它不能引用 Base 类?
class Base {
public:
void pub_mem(); // public member
protected:
int prot_mem; // protected member
private:
char priv_mem; // private member
};
struct Pub_Derv : public Base {
// legal
void memfcn(Base &b) { b = *this; }
};
struct Priv_Derv : private Base {
// legal
void memfcn(Base &b) { b = *this; }
};
struct Prot_Derv : protected Base {
// legal
void memfcn(Base &b) { b = *this; }
};
struct Derived_from_Public : public Pub_Derv {
// legal
void memfcn(Base &b) { b = *this; }
};
struct Derived_from_Private : public Priv_Derv {
// illegal
void memfcn(Base &b) { b = *this; }
};
struct Derived_from_Protected : public Prot_Derv {
// legal
void memfcn(Base &b) { b = *this; }
};
最佳答案
表达式
b = *this;
需要调用从 *this
到类型 Base
的左值的隐式转换,以便调用隐式声明的 Base::operator=(const Base& )
。此转换通过路径 Derived_from_Private -> Priv_Derv -> Base
。由于 Priv_Derv
将 Base
作为私有(private)基础,因此 Derived_from_Private
无权访问第二个链接。
关于c++ - 为什么这个派生类的定义是非法的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49060458/