当前位置:网站首页>4.1.4 why set the member variable to private
4.1.4 why set the member variable to private
2022-07-28 07:30:00 【123_ YQH】
Why declare member variables as private
Why encapsulate member variables as private, There are four main reasons :
① benefits 1: If the member variable is not public, The only way for customers to access member variables is through member functions . If public Everything in an interface is an interface function , Then customers do not need to consider whether to use when accessing classes (), Because everything is a function , All need to use ().
② benefits 2: It can make the processing of member variables more accurate . If you set the member variable to public Of , Then everyone can read and write it ; But if you declare it as private Of , You can realize according to your own needs “ No access to ”、“ Read only access ”、“ Write access only ”、“ Read and write access ”.
Such as : Precise control of encapsulated member variables can be achieved through the following member functions .
class AccessLevels {
public:
... // Constructors, etc
int getReadOnly() const {
return readOnly;
}
void setWriteOnly(int val) {
writeOnly = val;
}
void setReadWrite(int val) {
readWrite = val;
}
int getReadWrite() const {
return readWrite;
}
private:
int noAccess; // Forbidden member variables
int readOnly; // Read only member variables
int writeOnly; // Write only member variables
int readWrite; // Read and write member variables
};
③ benefits 3: encapsulation . If you access member variables through functions , You can replace this member variable with a calculation in the future , and class Users won't know at all class There have been changes inside , Provide more possibilities for the implementation of accessing member variables .
Such as : We want to access the average value of the array , One way is to set up a member variable of the average , And define a member function , Just return the value of the member variable each time ; Or another way , Member variables are not defined , Directly define a function to calculate the average , Calculate the average value at each call .
So when we change in order to save memory MyArray When the structure , Users can continue to call getAvg() The interface of , Instead of feeling that the class has actually changed .
// Method 1: Define the value of the member variable returned each time
class MyArray {
public:
... // Constructors, etc
int getAvg() const {
return avg;
}
private:
vector<int> arr;
int avg;
};
// Method 2: Member variables are not defined , Directly define a function to calculate the average
class MyArray {
public:
... // Constructors, etc
int getAvg() const {
int sum = 0;
for (int i : arr) {
sum += i;
}
return sum / arr.size();
}
private:
vector<int> arr;
};
benefits ④public and protected Means no encapsulation , Not encapsulated means that it cannot be changed . If you don't package , We will public or protected The member variable of is changed to private after , Will destroy a large number of user code .
Such as : Find the class of array average , We don't package , Users directly use these non encapsulated classes .
// Class that does not encapsulate the average value of the array
class MyArray {
public:
...// Other member functions
vector<int> arr;
int avg;
};
// user designation codes
int main() {
Myarray nums;
nums.arr.push_back(10);
nums.arr.push_back(10);
nums.arr.push_back(10);
cout << nums.avg << endl;
return 0;
}
When we later want to arr and avg become private You will find a large number of errors in the user's code , It will take a lot of effort to modify .
// Class that does not encapsulate the average value of the array
class MyArray {
public:
...// Other member functions
private:
vector<int> arr;
int avg;
};
// user designation codes
int main() {
Myarray nums;
nums.arr.push_back(10); // error : No access MyArray::arr Variable
nums.arr.push_back(10);
nums.arr.push_back(10);
cout << nums.avg << endl;
return 0;
}
边栏推荐
- C language review (modifier article)
- Redis sentinel mode and cluster
- Dynamic memory management knowledge points
- Essential performance optimization topics in the interview~
- Pytorch extracts the feature map of a certain layer
- 合并两个排序的链表——每日两题
- 微信小程序隐藏滚动条的方法
- 2018-cvpr-Gesture Recognition: Focus on the Hands
- Pytorch - storage and loading model
- 最早截止时间优先(EDF)
猜你喜欢

Redis主从复制原理及配置

最早截止时间优先(EDF)

Reasons why null is not recommended for MySQL fields

合并两个排序的链表——每日两题

Not used for the longest time recently

caffe fine tune

(每日一题)——最长不含重复字符的子字符串

The net loss of users occurred again, and China Mobile, which lost face, launched ultra-low price packages to win users

软考证书还能这样用!拿到证书=获得职称?

MHA high availability configuration and failover
随机推荐
Cdn.jsdelivr.net is not available, what should I do
项目经历总结
Pytorch extracts the feature map of a certain layer
guava之EventBus
Eslint FAQ solutions collection
C language: understand the creation and destruction of function stack frames through an example
JS upload file method
Pytorch installation - CPU version
JS secondary linkage Department
VCF file production
动态内存管理知识点
C language review (pointer)
GFS distributed file system
Retryer of guava
Two horizontal and vertical screen switching schemes for uniapp mobile terminal
分布式系分发展概览
低端电脑如何深度学习秘籍-使用mistGPU计算平台
链表中倒数第k个节点——双指
Redis sentinel mode and cluster
Continous Gesture Recognition with hand-orented spatiotemporal feature