当前位置:网站首页>4.1.4为什么要将成员变量设置为private
4.1.4为什么要将成员变量设置为private
2022-07-28 05:34:00 【123_YQH】
为什么要将成员变量声明为private
为什么要将成员变量封装为private,主要有以下四个原因:
①好处1:如果成员变量不是public,那么客户唯一能访问成员变量的唯一方式就是通过成员函数。如果public接口内的每样东西都是接口函数,那么客户在访问类是就不需要考虑用不用使用(),因为每样东西都是函数,都需要用()。
②好处2:可以使对成员变量的处理更加精确。如果你令成员变量为public的,那么每个人都可以读写它;但是如果你将它声明为private的,你可以根据自己需求实现“不准访问”、“只读访问”、“只写访问”、“读写访问”。
如:通过以下成员函数就可以实现对封装起来的成员变量的精准控制。
class AccessLevels {
public:
... //构造函数等
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; //禁止访问的成员变量
int readOnly; //只读成员变量
int writeOnly; //只写成员变量
int readWrite; //读写成员变量
};
③好处3:封装。如果你通过函数访问成员变量,日后可改以某个计算来替换这个成员变量,而class用户一点也不会知道class内部已经出现了变化,为访问成员变量的实现提供更多可能。
如:我们要访问数组的平均值,一种方法是设立一个平均值的成员变量,并且定义一个成员函数,每次只需要返回成员变量的值就行了;或者另一种方法,不定义成员变量,直接定义一个计算平均值的函数,每次调用的时候计算平均值。
这样当我们为了节省内存改变了MyArray结构时,用户可以继续调用getAvg()的接口,而不会感觉到类其实内部已经发生了变化。
//方法1:定义成员变量每次返回成员变量的值
class MyArray {
public:
... //构造函数等
int getAvg() const {
return avg;
}
private:
vector<int> arr;
int avg;
};
//方法2:不定义成员变量,直接定义一个计算平均值的函数
class MyArray {
public:
... //构造函数等
int getAvg() const {
int sum = 0;
for (int i : arr) {
sum += i;
}
return sum / arr.size();
}
private:
vector<int> arr;
};
好处④public和protected意味着不封装,不封装意味着不能改变。如果不封装,我们之后将public或protected的成员变量改变成private之后,将会破坏大量的用户的代码。
如:求数组平均值的类,我们不进行封装,用户直接使用了这些不封装的类。
//不封装的求数组平均值的类
class MyArray {
public:
...//其他成员函数
vector<int> arr;
int avg;
};
//用户代码
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;
}
当我们之后又想将arr和avg变成private时会发现用户的代码出现的大量的错误,如果要修改将会耗费大量的力气。
//不封装的求数组平均值的类
class MyArray {
public:
...//其他成员函数
private:
vector<int> arr;
int avg;
};
//用户代码
int main() {
Myarray nums;
nums.arr.push_back(10); //错误:没有权限访问MyArray::arr变量
nums.arr.push_back(10);
nums.arr.push_back(10);
cout << nums.avg << endl;
return 0;
}
边栏推荐
- 大话持久性与redolog
- Easypoi one to many, merge cells, and adapt the row height according to the content
- PyTorch - Dropout: A Simple Way to Prevent Neural Networks from Overfitting
- Implementation method of converting ast into word vector before converting word vector
- MHA高可用配置及故障切换
- How low-end computers learn secrets in depth - using the mistgpu computing platform
- Continous Gesture Recognition with hand-orented spatiotemporal feature
- Multiprocessing (multiprocessing)
- Basic usage and precautions of arrow function (= >) and three-point operator (...) in ES6 (this points to)
- 面试中必不可少的性能优化专题~
猜你喜欢

Leetcode then a deep copy of the linked list

caffe fine tune

学生执勤问题

Joern's code uses -devign

VLAN configuration

Overview of distributed system development

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

OJ questions about fast and slow pointers in linked lists

低端电脑如何深度学习秘籍-使用mistGPU计算平台

guava之EventBus
随机推荐
0727~面试题梳理
登录heroku出现 IP address mismatch的解决方案
Blueberry pie Bluetooth debugging process
Database-Trivial
分布式系分发展概览
Map uses tuple to realize multiple value values
NoSQL之Redis配置与优化
freemarker导出word,带表格和多张图片,解决图片重复和变形
VNC Timed out waiting for a response from the computer
Construction of Yum warehouse
Remotely access the local website of services such as neo4j on the ECS
A timed task reminder tool
Qucs preliminary use guide (not Multism)
软考证书还能这样用!拿到证书=获得职称?
Short work priority SJF
Pytorch extracts the feature map of a certain layer
The H5 input box of the mobile terminal adjusts the soft keyboard of the mobile phone, causing the fixed positioning at the bottom to be jacked up. Solution
Log in to heroku and the solution of IP address mismatch appears
easypoi一对多,合并单元格,并且根据内容自适应行高
nodejs操作MongoDB