C++的三种访问级别:
public :public的成员运行任何函数访问,不管他们是不是这个类的一部分
protected:protected成员只允许这个类本身及其子类成员函数访问
private:private成员只允许这个类本身的成员函数访问
三种继承方式的对比:
特征 公有继承 保护继承 私有继承
公有成员继成 派生类公有成员 派生类保护成员 派生类私有成员
私有成员继成 只能通过基类接口访问 只能通过基类接口访问 只能通过基类接口访问
保护成员继成 派生类保护成员 派生类保护成员 派生类私有成员
能否隐式转换 是 是(但只能在此派生类中) 否
父类中的所有成员,被子类继承以后,除了父类的构造器不能被继承外,其他函数,子类都会被继承,都可直接或间接的访问。对于公有成员,public继承后,可直接访问(如下的p.成员方式访问);私有成员,public继承后,只能间接访问。
#include<iostream>
#include<string.h>
#include<fstream>
using namespace std;
class point{
private:
int y;
public:
int x;
public:
point(int x,int y);
point();
int getY();
int getX();
void setY(int y){this->y=y;}
};
class ppoint:public point{
public:
int z;
public:
ppoint(int ,int,int);
void setZ(int z){this->z=z;}
int getZ() const{return this->z;}
};
int main(){
ppoint p(1,2,3);
cout<<p.x<<endl; //可直接访问
cout<<p.z<<endl; //直接访问
cout<<p.getY()<<endl; //y是私有的不可直接访问(p.y),只能通过getY()这个父类的公有函数获取y的值
}
ppoint::ppoint(int x,int z,int y){
this->x=x;
this->z=z;
this->setY(y); //也可写在main中p.setY(y)设置,为了统一,所有赋值操作放在构造器中,由于y是父类私有的,只能通过函数设置,this->y=y;是错误的
}
point::point(){
this->x=0;
this->y=0;
this->setY(0);
}
point::point(int x,int y){
this->y=y;
this->x=x;
}
int point::getY(){
return y;
}
int point::getX(){
return x;
}
若是private继承,父类的所有成员只能通过函数间接访问(父类的构造器不能被继承)
using namespace std;
class point{
private:
int y;
public:
int x;
public:
point(int x,int y);
point();
int getY();
int getX();
void setY(int y){this->y=y;}
};
class ppoint:private point{
public:
int z;
public:
ppoint(int ,int);
void setZ(int z){this->z=z;}
int getZ() const{return this->z;}
void print();
};
int main(){
ppoint p(1,2);
p.print();
cout<<p.getX()<<endl;//错误 ‘point’ is not an accessible base of ‘ppoint’</span>
}
void ppoint::print(){ //不能通过p.来访问
cout<<this->getX()<<endl; //只能在子类中把基类的成员包装起来通过p.包装函数 访问 也可通过this->x来打印结果
cout<<this->getY()<<endl; //只能通过函数访问,this->y错误
cout<<this->getZ()<<endl; //也可放在main中p.getZ()来访问
}
ppoint::ppoint(int x,int z,int y){
this->x=x; //正确
this->z=z;
this->setY(y); //this->y=y错误 x,y是父类的成员,一个私有一个公有,被继承后私有的只能通过函数访问
}
point::point(){
this->x=0;
this->y=0;
}
point::point(int x,int y){
this->y=y;
this->x=x;
}
int point::getY(){
return y;
}
int point::getX(){
return x;
}
对于私有成员,类中的函数可直接访问(this->函数/变量),子类中只能通过类中的其他函数间接访问。例如private继承的x ,y ,x在基类中公有,经过private
后私有化,但子类中的函数可直接对其访问,如ppoint构造器中的访问。而y在基类中已经是私有的,ppoint构造器也只能通过其对外的公有函数setY访问。