鉴于这种情况:
class GrandParent {};
class Parent : public GrandParent {};
class Child : public Parent {}; /// Ok
class Child : public GrandParent {}; /// Is it possible to force a compilation error?
Run Code Online (Sandbox Code Playgroud)
小智 39
使GrandParent构造函数成为私有和Parent朋友.
class GrandParent
{
friend class Parent;
private:
GrandParent() {}
// ...
};
Run Code Online (Sandbox Code Playgroud)
或者,您可以GrandParents 通过使析构函数私有来权衡多态破坏:
class GrandParent
{
friend class Parent;
private:
virtual ~GrandParent() {}
};
// Invalid Destruction:
GrandParent* p = new Parent;
...
delete p;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
991 次 |
| 最近记录: |