c++ - 关于多重继承和定义虚函数

标签 c++ multiple-inheritance virtual-functions

我有一个多重继承场景,没有像这样的虚拟基类:

 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/

相关文章:

c++ - 函数解析中使用的多重继承顺序?

c++ - 当对象具有值语义时,在方法中内联虚函数

python - 为什么Python的C3 MRO依赖于一个公共(public)基类?

c++ - QString 中的哪个函数对用于转换为 std::string 或从 std::string 转换?

c++ - 用\'替换字符串中的单引号

c++ - 如何在 C++ 的构造函数中定义一个 extern const

c++ - 继承只是为了共享枚举 - 危险吗?

c++ - 如何从派生类函数中调用虚函数

c++ - 是否需要重写一个以基类为参数的虚函数?

android - g++、c4droid 和拾取包括