您的位置:首页 > 编程语言 > C语言/C++

C++虚基类的作用及使用1

2013-12-31 14:53 267 查看


一.虚基类的何时使用:



如下程序所示,当son类,继承father类和mother类,并且father类继承自human类,mother也继承自human类.此时当son类对象调用human类中的公有变量或函数时,就要使用虚基类.由于son类直接继承自father类和mother类,而father类和mother类又继承自human类.所以son对象是理论上可以调用human这个基类成员的(含变量和函数).
由于father类和mother类都继承了human类,因此human类中的公有成员就被这2个类分别继承,这时son类继承father类和mother类,就说明son类通过2种途径继承了来自human类的成员.当我们引用son对象调用human类成员时,会出现通过father类继承调用了human类成员,同时也出现通过mother类继承调用了human类成员.这时编译器蒙圈了.它不知道怎么调用了.如下边代码的son1.bb这种调用.这个bb到底是通过father类继承调用human类的bb呢?还是通过mother类继承调用human类的bb呢?因此需要使用关键字virtual来定义虚基类.本例子的虚基类为human类.


二.虚基类的好处:

当发送上述情况时,由于将human类为虚基类,因此father类和mother类就会只有一方继承human类的成员,具体是father类还是mother类继承它的成员,这是编译器决定的.这个不追究.我们放在下边的重点上.这时son对象引用human类的成员,编译器就知道了是father类继承了human类的bb,或者是mother类继承了human类的bb,当然father类和mother类要取其一.这就不会出现错误.在"一.虚基类何时使用"时,提到"编译器不知道:son对象到底是通过father类继承的human类成员bb,还是通过mother类继承的human类成员bb."这里编译器就知道了:到底是哪一个类(这里指father类或mother类)引用了human类的成员bb.就不会出现不知道father类和mother类继承human类的bb的情况.这种歧义叫"两义性".为了好理解我们看下边的代码吧.

class human

{

public:

int bb;//这是虚基类演示的成员bb.

};

class father :

public human

{

public:

};

class mother :

public human

{

public:

};

class son :

public mother, public father

{

};

int _tmain(int argc, _TCHAR* argv[])

{

son son1;

son1.bb=1;//此处不使用虚基类时会出现错误.因为无法知道是通过father类继承得到的bb,还是mother继承得到的bb.

system("pause");

return 0;

}

这是vs2013错误提示:



这是使用了虚基类的代码,可以正常编译并使用.

class human

{

public:

int bb;//这是虚基类演示的成员bb.

void stand(){ cout << "human类输出"; }

};

class father :

virtual public human

{

public:

};

class mother :

virtual public human

{

public:

};

class son :

public mother, public father

{

};

int _tmain(int argc, _TCHAR* argv[])

{

son son1;

son1.bb=1;//此处不使用虚基类时会出现错误.因为无法知道是通过father类继承得到的bb,还是mother继承得到的bb.

son1.stand();

system("pause");

return 0;

}

从中可以看出,虚基类,主要是在 第一基类 派生 出第二基类,第二基类派生出派生类,这个派生类要使用第一基类的成员,这时候才使用虚基类.



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: