第4章---派生类与继承

1 、基类成员在派生类中的访问属性

       内部访问:基类为public、protected的无论继承方式都可在子类中访问

       对象访问:基类修饰类型在子类中转换为扩展类型,访问规则同

       ps:protected成员可以由本类或派生类的成员函数访问,而类外的任何访问都是非法的!


2、访问声明:对基类的私有成员不能使用访问声明

#include<iostream>
#include<string.h>
using namespace std;

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

class B: private A{
	private:
		int y;
	public:
		B(int x1, int y1):A(x1){//派生类构造函数
			y = y1;
		}
		A::print;
};
int main(){
	B b(10,66);
	b.print();//调用基类A的print()
	return 0;
}

3、虚基类

      为什么引入虚基类?

      当一个派生类的多个直接杰类是从另一个共同基类派生而来的,这些直接基类从上一级基类继承来的成员拥有相同的名字,在内存中存在多个拷贝,在派生类对象中,如何分辨?

       (1) 作用域标识符“::”

#include<iostream>
#include<string.h>
using namespace std;

class base{
	protected:
		int a;
	public:
		base(){
			a = 5;
			cout<<"base a= "<<a<<endl;
		}
};
class base1: public base{
	public:
		base1(){
			a = a + 10;
			cout<<"base1 a = "<<a<<endl;
		}
};
class base2: public base{
	public:
		base2(){
			a = a + 20;
			cout<<"base2 a = "<<a<<endl;
		}
};
class derived: public base1, public base2{
	public:
		derived(){
			cout<<"base1 a = "<<base1::a<<endl;//标识符区别
			cout<<"base2 a = "<<base2::a<<endl;
		}
};
int main(){
	derived obj;
	return 0;
}

输出:

base a= 5
base1 a = 15
base a= 5
base2 a = 25
base1 a = 15
base2 a = 25

       (2) virtual,虚基类,共同基类在内存中只有一个拷贝

#include<iostream>
#include<string.h>
using namespace std;

class base{
	protected:
		int a;
	public:
		base(){
			a = 5;
			cout<<"base a= "<<a<<endl;
		}
};
class base1: virtual public base{
	public:
		base1(){
			a = a + 10;
			cout<<"base1 a = "<<a<<endl;
		}
};
class base2: virtual public base{
	public:
		base2(){
			a = a + 20;
			cout<<"base2 a = "<<a<<endl;
		}
};
class derived: public base1, public base2{
	public:
		derived(){
			cout<<"derived a = "<<a<<endl;
                }
};
int main(){
	derived obj;
	return 0;
}

输出:

base a= 5
base1 a = 15
base2 a = 35
derived a = 35


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值
>