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

第十一章[2]:多继承中二义性的解决方案(类名+虚基类)

2016-08-21 21:11 274 查看
二义性定义:一个派生类有多个基类,对应的多个基类中有元素名称相同的元素的情况

下面是二义性的解决方案

【用类名解决】

/*

* 题目名称:二义性的解决方案应用

* 认为输出:class base1: x= = +10

* /class base2: x= = +20

* /class base2: x= = +30

* 实际输出:无

* 概论分析:二义性的解决

* 自己分析:一个基类+派生类:调用方式解决;多个基类用名称解决

* 表现形式

* 对象名.基类名::成员元素名+初始化

* 文本分析:没找到

* 评论:了解二义性的存在

* 难度系数:3

*/

#include <iostream>

using namespace std;
class base1

{

public:
int x;
void print()
{
cout<<"class base1: x= "<<x<<endl;
}

};
class base2

{

public:
int x;
void print()
{
cout<<"class base2: x= "<<x<<endl;
}

};
class derived:public base1,public base2

{

public:
int x;
void print()
{
cout<<"class derived: x= "<<x<<endl;
}

};

void main()

{
derived ob;
ob.x=10;
ob.print();
ob.base1::x=20; 
ob.base1::print();
ob.base2::x=30; 
ob.base2::print(); 
system("pause");

}


【虚基类解决方案】

定义
为了解决二义性而产生

声明形式
calss 派生类名:virtual 派生方式 基类名

备注
声明了虚基类后,虚基类成员在进一步派生过程中和派生类一起维护同一个内存拷贝。

代码
/** 题目名称:虚基类的应用

* 认为输出:constructing base,x=+1* /constructing base2,x=+1

* /constrcting  base1,x=+2

*/constructing base3,x=+2

* /constrcting derived x=+2*

* 概论分析:虚函数

* 自己分析:应该是一中特素的类,其特点是什么???

* 文本分析:为了解决基类中由于同名成员的问题

*         声明形式*calss 派生类名:virtual 派生方式 基类名

*        虚基类的定义只需要在基类的声明中,在继承方式前添加virtual关键字即可,编译系统将自动消除二义性。

 * 评论:只要是该继承的是没有被更改过的虚拟类,则元素按虚拟类中给出的数值来算,反之按该过的来算

* 难度系数:3*/

#include <iostream>

using namespace std;

class base

{

protected: 

    int x;

public:

base()


     x=1; 

cout << "constructing base,x=" << x << endl;  

       }

};

class base1:virtual public base

{

public:

     int x; 

      base1(){

                      x = 2;

     cout<<"constructing base1,x="<<x<<endl;

                    }

};

class base2:virtual public base

{

   public:

            base2() 

                       {

                           cout<<"constructing base2,x="<<x<<endl;

                       }

};

class base3:virtual public base,public base1



   public:

           base3() 

                    {  

                    cout<<"constructing base3,x="<<x<<endl; 

                   }

};

class derived:public base2,public base3

 {

     public:

            derived()

{

  cout<<"constrcting derived x="<<x<<endl;

  }

};

void main()



    derived obj; 

    system("pause");

}


多重定义了解即可,在项目中最好不要使用
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++