二义性 , 虚基类 virtual

版权声明:如需转载,请联系原作者授权... https://blog.csdn.net/Superman___007/article/details/82079049

二义性:向一个对象发送消息不明确。
发送消息:对象.成员

1、单继承:父子继承时,出现同名现象
    Class a;
    Class b:public a
    作用域的屏蔽:子类会屏蔽父类
解决二义性:作用域
    b.父类::父类成员

2、重写(覆盖):如果父子类出现同名且同形参方法,子类的作用域会覆盖父类。
  注:父类还是存在  

3、虚基类:
      关键字:   virtual 
      解决问题:防止公共基类中多继承中出现重复继承
        class A
        {
        };
        class B :virtual public A
        {
        }
        class C:virtual public A
        {
        };
        class  D:public B,public C   在D中出现公共基类问题
        {
        };
        注: 初始化必须由该子类(D:包含公基类)来构造公基类

#include<iostream>
#include<string>
using namespace std;
//共基类
class people
{
public:
	//无参构造器
	people(){}
	people(int i,const char* n):id(i),name(n)
	{
	}
	void show()
	{
		cout<<"people::"<<"id:"<<id<<" name:"<<name;
	}
protected:
	int id;
	string name;
};

//学生类:people
class student:virtual public people
{
public:	//构造:子类构造自己和继承(父类的构造方法)
	student(int i,const char* n,short s):people(i,n),score(s)
	{
	}
	void display()
	{
		cout<<"student::";
		this->show();
		cout<<" score:"<<score<<endl;
	}
protected:
	short score;
};
//老师类:人类
class teacher:virtual public people
{
public:
	teacher(int i,const char* n,int g):people(i,n),grade(g){}
	void display()
	{
		cout<<"teacher::";
		this->show();
		cout<<" grade:"<<grade<<endl;
	}
protected:
	int grade;//年级
};
//博士:学生,老师
class doctor:public student,public teacher
{
public:
	doctor(int i,const char* n,int se,int g,const char* sch):school(sch),student(1001,n,se),teacher(2001,n,g),people(i,n){}
	
protected:
	string school;//学校
};

int main()
{
	doctor zn(1001,"zn",1001,3,"中科大");
	//zn.display();//	二义性(doctor有两个display)
	zn.teacher::display();//输出tacher中的show方法
	zn.student::display();//输出student中的show方法
	//输出ID和姓名
	//zn.people::show();//因为有两份people::show
	zn.teacher::show();
	zn.show();//由于该类中有一份拷贝 

	cout<<endl<<sizeof(zn)<<endl;	
}

  上图中Student 类和Teacher类都继承了people类(共基类) , 所以在继承的时候需要 virtual 来继承(虚基类) , 这样就会为子类申请一个指针空间来指向共基类的地址 , Student类会申请一个指针 , Teacher也会申请一个指针 .  

图中的Student   和   Teacher  都会初始化一次people  ,  为了避免出现这种错误 , 所以需要people  自己来初始化 .

  所以  :  doctor(int i,const char* n,int se,int g,const char* sch):school(sch),student(1001,n,se),teacher(2001,n,g),people(i,n){}

猜你喜欢

转载自blog.csdn.net/Superman___007/article/details/82079049
今日推荐