将父级设置为私有级,将祖父母级设置为公共级

Making the parent private and the grandparent public for a class

本文关键字:设置 祖父母      更新时间:2023-10-16

短篇小说:

可以做吗

class A{};
class B:public virtual A{}; 
class C:public virtual A,private B{};

即"表明"C是A而不是B,但使其实际上是B而不添加虚拟(和相应的vptrs)?

长话短说:A有几种方法。B又加了一些。有时我想禁止使用其中一个。C有这个目的。这个项目有很多B,很少有C。我不想让B成为C.的子类

是的,这将完全按照您的意愿进行。但考虑另一种选择:公开继承并隐藏不需要的方法:

class A
{
public:
    int a() {return 0xaa;}
};
class B: public A
{
public:
    int b() {return 0xbb;}
};
class C: public B
{
private:
    using B::b; // makes the method called b private
};
...
B().b(); // OK, using method b in class B
C().b(); // error: b is private in class C
C().B::b(); // OK: calling b in base-class (not sure if you want to prevent this)

这将同时适用于虚拟继承和非虚拟继承。