我有三个名为 A、B 和 C 的类。B 继承自 A,C 继承自 B。(A -> B -> C)。
我还有一个名为 IBinary 的抽象基类。我想让所有的类都实现 IBinary 接口。当我让 A 类继承自 IBinary 时,我的代码输出为C::readb
. 当 A 类不继承自 IBinary 时,输出为B:readb
.
让我的三个类订阅相同接口的正确方法是什么?如果我只有从接口类继承的顶级类(A),我需要重构我的代码,这样我就不会像上面那样遇到解析问题。
如果我明确地让所有类都从接口类继承,那么我将拥有一个更复杂的类层次结构,并且更接近于拥有一颗死亡钻石。
#include <iostream>
class IBinary {
public:
virtual void readb( std::istream& in ) = 0;
};
// Basic A -- change whether this inherits from IBinary
class A : public IBinary {
public:
A() {};
void readb( std::istream& in ) {}
};
// Specialized A
class B : public A {
public:
B() {};
void load() {
this->readb(std::cin); // <-- which readb is called?
}
void readb( std::istream& in ) {
std::cout << "B::readb" << std::endl;
}
};
// Specialized B
class C : public B {
public:
C() {};
void readb( std::istream& in ) {
std::cout << "C::readb" << std::endl;
}
void foo() {
B::load();
}
};
int main() {
C c;
c.foo();
}