c++ - 为什么这个派生类的定义是非法的?

标签 c++ class c++11 inheritance

为什么派生类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_DervBase 作为私有(private)基础,因此 Derived_from_Private 无权访问第二个链接。

关于c++ - 为什么这个派生类的定义是非法的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49060458/

相关文章:

ruby-on-rails - 根据枚举更改类颜色

c++ - 如何为其构造函数采用右值的类声明变量?

c++ - 从字节和切片中获取位 2 位对

c++ - 在字符串中使用空字符 (C++)

c++ - QDialog创建后闪退

c++ - 这个重新分配是否正确?

powershell - 如何在 PowerShell 中创建私有(private)类成员?

c++ - 从这里实例化的类错误c++

java - 尽管实现了,具体类方法仍然从抽象类中抛出异常

c++ - 模板类的友元运算符