代码改变世界

C++中虚基类 Virtual Base Class 的作用

2011-10-23 12:39  zhiyzhan  阅读(705)  评论(0编辑  收藏  举报

Virtual base classes (C++ only)

Suppose you have two derived classes B and C that have a common base class A, and you also have another class D that inherits from B and C. You can declare the base class A as virtual to ensure that B and C share the same subobject of A.

In the following example, an object of class D has two distinct subobjects of class L, one through class B1 and another through class B2. You can use the keyword virtual in front of the base class specifiers in the base lists of classes B1 and B2 to indicate that only one subobject of type L, shared by class B1 and class B2, exists.

For example:

Virtual base classes 1
class L { /* ... */ }; // indirect base class
class B1 : virtual public L { /* ... */ };
class B2 : virtual public L { /* ... */ };
class D : public B1, public B2 { /* ... */ }; // valid

Using the keyword virtual in this example ensures that an object of class D inherits only one subobject of class L.

A derived class can have both virtual and nonvirtual base classes. For example:

Virtual base classes 2
class V { /* ... */ };
class B1 : virtual public V { /* ... */ };
class B2 : virtual public V { /* ... */ };
class B3 : public V { /* ... */ };
class X : public B1, public B2, public B3 { /* ... */
};

In the above example, class X has two subobjects of class V, one that is shared by classes B1 and B2 and one through class B3.

#include <iostream.h>
class A
{
public:
void print() {cout<<"你好\n";}
};
class B: virtual public A
{
};
class C:virtual public A
{
};
class D:public B,public C
{
};
void main()
{
D a;
a.print();

a.B::print();
a.A::print();
}

class C:virtual public A class B:virtual public A

虚基类是一种声明,他告诉编译器,如果同时有多个类继承虚基类而这多个类又同时被一个类所继承,那么这个类只获得虚基类的一份拷贝从而避免了二义性。仅仅就是这样一种声明,就是向编译器打了个招呼以避免子类继承了多份拷贝这种情况的发生

参考:http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr142.htm

http://wenwen.soso.com/z/q176593369.htm