我有一个类树来:部分隐藏继承树
class A;
class B : public A;
然后我想创建是从B类派生的类,但我想那推导从外部成员隐蔽以及任何人从C类继承
class C : private B;
void test() {
C c;
B *b = &c; // compiler error: B in C is private and is therefore not type compatible. This is desired.
}
不过,我也想展示A级隐藏B类的继承在这种情况下还隐藏A类
void test2() {
C c;
A *a = &c; // Compiler error: A is only accessible through B which is not possible with a private inheritance of B. This is not desired; this conversion should be possible.
}
我可以再次从A继承,但是如果A有任何变量,那显然会创建重复的成员变量。我可以创建一个类A的虚拟继承,但我不觉得它会有我期望的确切效果,因为这会影响整个树而不是此段(对吧?)
我想明显的解决方案是创建一个类型转换成员函数:
class C : private B {
A * turn_into_A() {
// Since B is an A and we are still in the scope of C, this will succeed
return this;
}
};
不过,我更愿意避免明确的类型转换,如这种情况下,
任何理智的人会告诉我,我这样做是错误的。他们可能是对的。但为了知识的缘故,我只想知道:有没有一种方法可以在没有虚拟继承或显式成员函数的类型转换的情况下执行此操作?
@milleniumbug哈,错误的问题。 Apoligies。 – juanchopanza
幸运的是,您留下了一个免费的朋友功能进行类型转换的可能性。 –