【发布时间】:2011-08-20 04:22:39
【问题描述】:
我有一个多重继承场景,没有像这样的虚拟基类:
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 本身在其自己的公共方法中调用。 修改了示例,所以可能更清楚我想要做什么......
【问题讨论】:
标签: c++ multiple-inheritance virtual-functions