Col*_*len 5 c++ inheritance class
我想在派生类的私有基类中创建一个公共成员,如下所示:
class A {
public:
int x;
int y;
};
class B : public A {
// x is still public
private:
// y is now private
using y;
};
Run Code Online (Sandbox Code Playgroud)
但显然"使用"不能以这种方式使用.有没有办法在C++中这样做?
(我不能使用私有继承,因为A的其他成员和函数必须仍然是公共的.)
简短的回答:不。里氏替换和公共继承的性质要求你可以用 an A(即它的公共成员)做的一切也可以通过 来完成B。这意味着您无法隐藏公共方法。
如果你想隐藏 public fields,你无能为力。要“隐藏”公共方法,您可以执行以下操作:
class B {
// x is still public
int x() { return a.x(); }
private:
A a;
// y is now private since you didn't add a forwarding method for it
};
Run Code Online (Sandbox Code Playgroud)