我有命名为A三个类,B,和C. B,从A继承和C从B.继承(A - >乙 - > C)。正确继承设计
我也有一个名为IBinary的抽象基类。我想让所有的类都实现IBinary接口。当我从IBinary进行A类继承时,我的代码的输出是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();
}
我不明白这个问题。你想要什么* c.foo'做什么? –
一个类订阅接口是什么意思? – Casey
@Casey我正在使用订阅意味着实现。我想执行更清楚。 – Derek