短篇小说:
有没有可能做
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)
这将适用于虚拟和非虚拟继承。
关于c++ - 将父类设为私有(private),将祖 parent 设为公有类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9894331/