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

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();
}

20100125222257-1268839405.jpg

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

转载于:https://www.cnblogs.com/zhiyzhan/archive/2011/10/23/2221703.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值