问题
- class A has a pure virtual method
read()
- class B has an implemented virtual method
read()
- I have a class C that inherits A and B
- Can this happen?
What I'm trying to achieve is that the two base classes A and B complement each other.
So C read()
method would actually call class B read()
class A {
virtual int get_data() = 0;
void print() {
log(get_data());
}
}
class B {
virtual int get_data() {
return 4;
}
}
class C : public A, public B {
}
C my_class;
my_class.print(); // should log 4;
I'm not on my computer nor will have opportunity in the next couple of weeks so I can't test this... but I'm designing the architecture and needed to know if this is possible and if not.. how can this be accomplished!
回答1:
Can multiple base classes have the same virtual method?
- Can this happen?
Yes.
So C read() method would actually call class B read()
That doesn't happen automatically. A member function of base doesn't override a function of an unrelated base.
You can add an override to C
:
class C : public A, public B {
int get_data() override;
}
This overrides both A::get_data
and B::get_data
. In order to "actually call class B read()", you can indeed make such call:
int C::get_data() {
return B::get_data();
}
Or... that would be possible if you hadn't declared B::get_data
private.
Overriding a function in another base without explicitly delegating in derived is possible if you change your hierarchy a bit. In particular, you need a common base, and virtual inheritance:
struct Base {
virtual int get_data() = 0;
};
struct A : virtual Base {
void print() {
std::cout << get_data();
}
};
struct B : virtual Base {
int get_data() override {
return 4;
}
};
struct C : A, B {};
来源:https://stackoverflow.com/questions/55445840/can-multiple-base-classes-have-the-same-virtual-method