在这种情况下:
class GrandParent {};
class Parent : public GrandParent {};
class Child : public Parent {}; /// Ok
class Child : public GrandParent {}; /// Is it possible to force a compilation error?
最佳答案
将GrandParent
构造函数设为私有(private),并将Parent
设为 friend 。
class GrandParent
{
friend class Parent;
private:
GrandParent() {}
// ...
};
另外,您可以通过将析构函数设为私有(private)来权衡
GrandParents
的多态破坏:class GrandParent
{
friend class Parent;
private:
virtual ~GrandParent() {}
};
// Invalid Destruction:
GrandParent* p = new Parent;
...
delete p;