我有一个多重继承场景,没有像这样的虚拟基类:
Ta Tb
| |
B C
\ /
A
Ta 和 Tb 是两个不同的模板类,它们都声明了一个名为 f() 的虚函数。我想在 A 范围内覆盖这两个函数,因为我必须在这些方法中与 B 和 C 数据进行交互。但我不知道该怎么做。
class Tb {
protected:
virtual void f() {};
public:
void call() {
this->f();
};
};
class Tc {
protected:
virtual void f() {};
public:
void call() {
this->f();
};
};
class B : public Tb {
public:
void doSomething() {};
};
class C : public Tc {
private:
int c;
public:
void inc() { c++; };
};
class A : public B, public C {
protected:
void f() { // this is legal but I don't want to override both with the same definition.
// code here
}
// if Tb::f() is called then i want to call C::inc()
// if Tc::f() is called then i want to call B::doSomething()
public:
void call() {
B::call();
C::call();
};
};
是否有一种语法可以用不同的定义覆盖这两种方法,还是我必须在 B 和 C 中定义它们?
谢谢
编辑: 我的问题不是不能调用 Tb::f() 或 Tc::f(),而是如果调用 Tb::f() 或 Tc::f(),我想定义两种不同的行为。这些方法由 Tb 和 Tc 本身在其自己的公共(public)方法中调用。 修改了示例,所以可能更清楚我想要做什么......
最佳答案
Is there a syntax to override both the methods with different definitions or do I have to define these in B and C?
简短回答:不。
您的 A:f()
将覆盖 Ta::f()
和 Tb::f()
。
如果您想要不同的覆盖,唯一的解决方案是插入辅助类 Hb 和 Hc:
Ta Tb
| |
B C
| |
Hb Hc
\ /
A
Hb
可以小到两个函数,只是为了重命名函数:
class Hb: public B {
protected: // overrides from Ta
virtual void f() { Ta_f(); }
protected: // new virtuals
virtual void Ta_f() = 0;
};
然后你可以定义 A::Ta_f()
做任何你想做的事(包括调用 B::f()
!)
关于c++ - 关于多重继承和定义虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5911716/