当前位置:网站首页>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;
}
边栏推荐
- CAS vs 数据库乐观锁
- Redis sentinel mode and cluster
- MySQL excludes holidays and calculates the date difference
- OJ questions about fast and slow pointers in linked lists
- Easypoi one to many, merge cells, and adapt the row height according to the content
- C language: understand the creation and destruction of function stack frames through an example
- Review of C language (byte alignment)
- Nrf51822 review summary
- 分布式系分发展概览
- After learning the four redis cluster solutions at one go, each has its own merits
猜你喜欢
随机推荐
Two horizontal and vertical screen switching schemes for uniapp mobile terminal
Eslint FAQ solutions collection
Use of C3d
guava之限流RateLimiter
Image segmentation method
Softmax multi classification gradient derivation
Shell--- function
Deployment of elk log analysis system
Current limiting ratelimiter of guava
After learning the four redis cluster solutions at one go, each has its own merits
The.Joernindex database has no content after Joern runs
[a little knowledge] AQS
Remotely access the local website of services such as neo4j on the ECS
Review of C language (byte alignment)
Redis sentinel mode and cluster
Codesensor: convert the code into AST and then into text vector
map使用tuple实现多value值
Shell--- circular statement practice
WiFi one click connection configuration of raspberry pie
Shell -- first day homework









