1. 继承访问控制
1. 不能直接拿父亲的私房钱:派生类不能访问基类的私有成员
#include <stdio.h>
#include <iostream>
using namespace std;
class Father {
private:
int money;
public:
int getMoney(void){
return money;
}
void setMoney(int m){
this->money = m;
}
void it_skill(void){
cout<<"father`s it skill"<<endl;
}
};
class Son : public Father{
private:
int toy;
public:
void playGame(void){
cout<<"son play game"<<endl;
}
};
int main()
{
Son s;
s.setMoney(10);
cout<<"s get money = "<<s.getMoney()<<endl;
s.it_skill();
s.playGame();
system("pause");
return 0;
}
2. 可以问父亲要钱:通过protected/public的成员函数
class Son : public Father{
private:
int toy;
public:
void playGame(void){
int m;
cout<<"son play game"<<endl;
m = getMoney();
m--;
setMoney(10);
}
};
3. 儿子总是比外人亲:派生类可以访问父类的protected成员,其他代码不可以
#include <stdio.h>
#include <iostream>
using namespace std;
class Father {
private:
int money;
protected:
int roomkey;
public:
int getMoney(void){
return money;
}
void setMoney(int m){
this->money = m;
}
void it_skill(void){
cout<<"father`s it skill"<<endl;
}
};
class Son : public Father{
private:
int toy;
public:
void playGame(void){
int m;
cout<<"son play game"<<endl;
m = getMoney();
m--;
setMoney(10);
roomkey = 1;
}
};
int main()
{
Son s;
s.setMoney(10);
cout<<"s get money = "<<s.getMoney()<<endl;
s.it_skill();
s.playGame();
system("pause");
return 0;
}
roomkey是父类中protected成员,可以在子类中调用,其他地方不行
2. 调整访问控制
儿子继承来的财产,他可以捐给别人,也可以私藏(前提:Son看得见这些财产):
Son可见到的成员,Son可以修改它的权限。private: using Father::getMoney;
#include <stdio.h>
#include <iostream>
using namespace std;
class Father {
private:
int money;
protected:
int roomkey;
public:
int getMoney(void){
return money;
}
void setMoney(int m){
this->money = m;
}
void it_skill(void){
cout<<"father`s it skill"<<endl;
}
};
class Son : public Father{
private:
int toy;
public:
using Father::roomkey;
void playGame(void){
int m;
cout<<"son play game"<<endl;
m = getMoney();
m--;
setMoney(10);
roomkey = 1;
}
};
int main()
{
Son s;
s.setMoney(10);
cout<<"s get money = "<<s.getMoney()<<endl;
s.it_skill();
s.playGame();
s.roomkey = 1;
system("pause");
return 0;
}
3. 继承访问控制
1.无论哪种继承方式,在派生类内部使用父类时并无差别
2. 不同的继承方式,会影响这两方面:外部代码对派生类的使用、派生类的子类