4-1數(shù)據(jù)的封裝
1.如何進(jìn)行數(shù)據(jù)封裝
? 未進(jìn)行數(shù)據(jù)的封裝狭魂,成員變量容易發(fā)生數(shù)據(jù)的泄露:
數(shù)據(jù)的封裝1.png
?
進(jìn)行數(shù)據(jù)的封裝(這是面向?qū)ο蟮乃枷耄┦鸷疲蓡T變量設(shè)為private屬性,只能通過set和get方法來賦值和取值,提高了數(shù)據(jù)的安全性:
數(shù)據(jù)的封裝2.png
2.封裝的好處
? (1)可以對(duì)成員變量的賦值范圍進(jìn)行限制
? 未封裝:
數(shù)據(jù)的封裝3.png
`封裝后:`
數(shù)據(jù)的封裝4.png
? (2)限定成員變量只可讀取不可設(shè)置
? 只提供get方法不提供set方法:
數(shù)據(jù)的封裝5.png
3.代碼演示
#include <iostream>
#include <string>
using namespace std;
/**
* 定義類:Student
* 數(shù)據(jù)成員:名字、性別、學(xué)分昔榴、學(xué)習(xí)
*/
class Student
{
public:
void setName(string _name){//類內(nèi)定義方法
m_strName = _name;
}
string getName(){
return m_strName;
}
void setGender(string _gender){
m_strGender = _gender;
}
string getGender(){
return m_strGender;
}
double getScore(){
return m_dScore;
}
void initScore(){
m_dScore = 0.0;
}
void study(double _score){
m_dScore += _score;
}
private:
string m_strName;
string m_strGender;
double m_dScore;
};
int main()
{
// 實(shí)例化一個(gè)Student對(duì)象stu
Student stu;
stu.initScore();
// 設(shè)置對(duì)象的數(shù)據(jù)成員
stu.setName("青陽");
stu.setGender("男");
stu.study(5.0);
stu.study(3.0);
// 通過cout打印stu對(duì)象的數(shù)據(jù)成員
cout << stu.getName() << " " << stu.getGender() << " " << stu.getScore() << endl;
system("pause");
return 0;
}