在这种情况下:

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;

07-24 14:37