共有继承:
基类的public和protected在派生类还是public和protected。
保护继承:
基类的public和protected在派生类为protected。
私有继承:
基类的public和protected在派生类为private。
基类的private成员在派生类不可见
例如:
#include <iostream>
using namespace std;
class Base
{
public:
Base();
~Base();
public:
int a;
protected:
int b;
private:
int c;
};
class Son:public Base
{
public:
Son();
~Son();
void setA1(){aa=a;}//正确
void setA2(){aa=b;}//正确
void setA3(){aa=c;}//错误,基类private成员在派生类不可见
public:
int aa;
};
int main()
{
return 0;
}
根据访问权限总结出不同的访问类型,如下所示:
访问 | public | protected | private |
同一个类 | yes | yes | yes |
派生类 | yes | yes | no |
外部类 | yes | no | no |
外部类只能通过共有成员函数访问类内部的成员变量,如下面例子:
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
class testA
{
public:
testA(){cout<<"gou jian"<<endl;};
~testA(){};
void setA(int ma){a=ma;}
void setB(int mb){b=mb;}
void setC(int mc){c=mc;}
public:
int getA(){return a;}
protected:
int getB(){return b;}
private:
int getC(){return c;}
public:
int a;
protected:
int b;
private:
int c;
};
int main()
{
testA *test = new testA();
test->setA(1);
test->setB(2);
test->setC(3);
//在类的外部,public成员函数可用
int aa=test->getA();
cout<<"aa = "<<aa<<endl;
//error 在类的外部,protected成员函数不可用
int bb=test->getB();
cout<<"bb = "<<bb<<endl;
//error 在类的外部,private成员函数不可用
int cc=test->getC();
cout<<"cc = "<<cc<<endl;
return 0;
}