抽象基类,多重继承和常见的纯虚方法 [英] abstract base classes, multiple inheritence, and common pure virtual methods

查看:89
本文介绍了抽象基类,多重继承和常见的纯虚方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下测试代码似乎表明,如果一个类具有两个具有通用纯虚方法的抽象基类,则这些方法在派生类中是共享的".

The following test code seems to indicate that if a class has two abstract base classes with common pure virtual methods, then these methods are "shared" in the derived class.

#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(公认的旧版本)中干净地编译.输出为:

This code compiles cleanly in g++ 4.1.2 (admittedly old), using -std=c++98 -pedantic -Wall -Wextra -Werror. The output is:

A1
B1
AB1
A2
B2
AB2
A3
B3
AB3

这是我想要的,但是我怀疑这是正常的还是只是偶然"的.从根本上来说,这是我的问题:对于这种情况,我可以依靠这种行为吗?还是应该始终从虚拟基类继承?

This is what I desire, but I question whether this works generally, or only "by accident." Fundamentally, this is my question: can I depend on this behavior, or should I always inherit from a virtual base class for this type of scenario?

推荐答案

不要让它变得更难.与基类中的虚函数具有相同签名的函数将覆盖基版本.不管有多少个碱基,或者另一个碱基是否具有具有相同签名的虚函数,都没有关系.所以,是的,这行得通.

Don't make it harder than it is. A function with the same signature as a virtual function in a base class overrides the base version. Doesn't matter how many bases you have, or whether another base has a virtual function with the same signature. So, yes, this works.

这篇关于抽象基类,多重继承和常见的纯虚方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆