2

下面的测试代码似乎表明,如果一个类有两个具有公共纯虚方法的抽象基类,那么这些方法在派生类中是“共享的”。

#include <iostream>
#include <string>

using namespace std;

struct A
{
    virtual string do_a() const = 0;
    virtual void set_foo(int x) = 0;
    virtual int get_foo() const = 0;
    virtual ~A() {}
};

struct B
{
    virtual string do_b() const = 0;
    virtual void set_foo(int x) = 0;
    virtual int get_foo() const = 0;
    virtual ~B() {}
};

struct C : public A, public B
{
    C() : foo(0) {}
    string do_a() const { return "A"; }
    string do_b() const { return "B"; }
    void set_foo(int x) { foo = x; }
    int get_foo() const { return foo; }
    int foo;
};

int main()
{
    C c;
    A& a = c;
    B& b = c;
    c.set_foo(1);
    cout << a.do_a() << a.get_foo() << endl;
    cout << b.do_b() << b.get_foo() << endl;
    cout << c.do_a() << c.do_b() << c.get_foo() << endl;
    a.set_foo(2);
    cout << a.do_a() << a.get_foo() << endl;
    cout << b.do_b() << b.get_foo() << endl;
    cout << c.do_a() << c.do_b() << c.get_foo() << endl;
    b.set_foo(3);
    cout << a.do_a() << a.get_foo() << endl;
    cout << b.do_b() << b.get_foo() << endl;
    cout << c.do_a() << c.do_b() << c.get_foo() << endl;
}

此代码使用 -std=c++98 -pedantic -Wall -Wextra -Werror 在 g++ 4.1.2(诚然旧)中干净地编译。输出是:

A1
B1
AB1
A2
B2
AB2
A3
B3
AB3

这是我想要的,但我质疑这是否普遍有效,或者只是“偶然”。从根本上说,这是我的问题:我可以依赖这种行为,还是应该始终从虚拟基类继承这种场景?

4

1 回答 1

3

不要让它变得比现在更难。与基类中的虚函数具有相同签名的函数会覆盖基版本。不管你有多少个碱基,或者另一个碱基是否有一个具有相同签名的虚函数。所以,是的,这行得通。

于 2013-04-16T15:09:16.550 回答