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