当前位置:网站首页>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;
}
边栏推荐
猜你喜欢

JS upload file method

On deep paging

一口气学完4种 Redis 集群方案,真是各有千秋

Soft exam certificate can be used like this! Get a certificate = get a professional title?

Image segmentation method

guava之guava cache
![[JVM optimization ultra detailed] common JVM tuning scenarios](/img/dd/3fed0b2bb6f00e5719982e38495e5c.jpg)
[JVM optimization ultra detailed] common JVM tuning scenarios

学生执勤问题

教程篇(7.0) 06. 零信任网络访问ZTNA * FortiClient EMS * Fortinet 网络安全专家 NSE 5

Deeply analyze the implementation of singleton mode
随机推荐
Database-Trivial
两个链表的第一个公共节点——每日两题
Safflower STL
How to connect the uniapp project to the real mobile phone for debugging
Blueberry pie Bluetooth debugging process
Isolation level RR, gap lock, unreal reading
map使用tuple实现多value值
大话持久性与redolog
[untitled]
低端电脑如何深度学习秘籍-使用mistGPU计算平台
(每日一题)——最长不含重复字符的子字符串
JS upload file method
User mode vs kernel mode, process vs thread
Student duty problems
ASP.NET Core 技术内幕与项目实战读后感
object detection
Overview of distributed system development
用户态vs内核态、进程vs线程
ThreadLocal那些事
Eslint FAQ solutions collection