9.c++面向對象編程-訪問控制和繼承

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. 不同的繼承方式,會影響這兩方面:外部代碼對派生類的使用、派生類的子類

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章