【发布时间】:2013-04-09 01:21:44
【问题描述】:
下面的测试代码似乎表明,如果一个类有两个具有公共纯虚方法的抽象基类,那么这些方法在派生类中是“共享的”。
#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
这是我想要的,但我怀疑这是否普遍有效,或者只是“偶然”。从根本上说,这是我的问题:我可以依赖这种行为,还是应该始终从虚拟基类继承这种类型的场景?
【问题讨论】:
-
这确实是 C++ 的工作方式。你可以依赖它,尽管我个人觉得这很危险(就像与多重继承有关的任何事情,就此而言,但这只是我。有时我们真的别无选择......)。跨度>
-
这是正确的 C++ 编译器的基本行为。甚至更旧或更新的编译器也是如此。 :-)
-
@syam 熟悉术语“最终覆盖者”并查看标准中的第 10.3 节。可能会解决一些混乱。
-
@CaptainObvlious 感谢您的指点。
标签: c++ abstract-class multiple-inheritance