c++ - 将父类设为私有(private),将祖 parent 设为公有类

标签 c++ inheritance

短篇小说:

有没有可能做

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/

相关文章:

c++ - 一个类的某些成员是否只能由基类访问?

c++ - 如何在 Qt 中获取 Windows 默认文件夹的本地化名称

java - Android扩展Activity

inheritance - 在 child 的构造函数中初始化抽象类字段

c++ - std::enable_if 和通用引用的使用差异

c++ - fatal error : opencv2/contrib/contrib. 未找到 hpp 文件(打开已构建的 cv)

c++ - 使模板接受特定的类/类族?

c++ - 是否允许 unique_prts 隐式转换其包含类型?

python - 在 Python 中,派生类可以被截断为基类吗?

typescript - 如何正确覆盖 typescript 中的方法?