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

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

问题描述

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

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天全站免登陆