C++ 如何使用公共函数访问私有变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20551206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:12:06  来源:igfitidea点击:

How do you access private variables using public functions?

c++functionmethodsprivatepublic

提问by Jim Jam

So I don't know if you any of you have been/goes on the NewBoston.Com (great resource by the way), but I was watching this video and the teacher was saying how you can access private info using public functions...

所以我不知道你们中是否有人去过/访问过 NewBoston.Com(顺便说一下,这是一个很好的资源),但我正在看这个视频,老师说你如何使用公共功能访问私人信息.. .

This is the video: http://www.youtube.com/watch?v=jTS7JTud1qQ

这是视频:http: //www.youtube.com/watch?v=jTS7JTud1qQ

And of course, just skip to the end to get to the gist of it.

当然,只需跳到最后即可了解其要点。

The thing I don't get though, is how can you access private information using a public function. If you make a function that's public that allows anyone to set the name, and get that name, then isn't it just public anyway?, Wouldn't anyone be able to mess my code and my desired output?

我不明白的是,您如何使用公共功能访问私人信息。如果您创建一个允许任何人设置名称并获取该名称的公开函数,那么它不就是公开的吗?,难道没有人能够弄乱我的代码和我想要的输出吗?

回答by SJuan76

The point of providing a public method to change a private variable is that you can add additional controls.

提供公共方法来更改私有变量的要点是您可以添加其他控件。

There is not a lot of difference between

之间没有太大区别

class A {
   public:
      int age;
}

and

class B {
   private:
      int age;
   public:
      void setAge(int _age);
}

B::setAge(int _age) {
   this->age = _age;
}

But, in the second case, you can add logic that rejects some data (v.g. a negative value) or updates other fields. So you can ensure that the data of your object will remain consistent. If you follow the first approach, that logic should replicated every time the property is accessed directly (note: many programmers will forget to do so).

但是,在第二种情况下,您可以添加拒绝某些数据(vg 为负值)或更新其他字段的逻辑。因此,您可以确保对象的数据保持一致。如果您遵循第一种方法,则每次直接访问属性时都应复制该逻辑(注意:许多程序员会忘记这样做)。

回答by Rajiv

Creating trivial getters and setters (public functions) is a bit futile in my opinion. If your class functionality is fully expressed by the private variables, then trivial getters and setters are a waste and somewhat of a code smell. Maybe you should use a struct instead.

在我看来,创建简单的 getter 和 setter(公共函数)有点徒劳。如果您的类功能完全由私有变量表达,那么琐碎的 getter 和 setter 是一种浪费并且有点代码味道。也许您应该改用结构体。

However public functions can provide an interface that guides the usage of the class and restricts what you can do with the private members. You do not want users of your class to change individual private members that only make sense when changed in sync step.

然而,公共函数可以提供一个接口来指导类的使用并限制您可以对私有成员执行的操作。您不希望您班级的用户更改仅在同步步骤中更改时才有意义的个人私有成员。

It also lets the implementation change, without changing the interface. For example say you want to increase the size of a hash map. Pseudo code:

它还允许实现更改,而无需更改接口。例如,假设您想增加哈希映射的大小。伪代码:

class IntHashMap {
public:
void increaseSize(int size);
// Other stuff.

private:
int* backing_array_ ;
int size_;
}

Now your implementation for increaseSize()can actually check if the new size is greater than the previous one. It can also actually create a new backing_array and copy the data over. Exposing the private variable size would achieve neither the check for proper value of size, nor the allocation of the new backing array.

现在您的实现increaseSize()实际上可以检查新大小是否大于前一个大小。它实际上也可以创建一个新的 backing_array 并复制数据。公开私有变量 size 既不能检查正确的大小值,也不能分配新的后备数组。

回答by Bartek Banachewicz

If you weren't able to access private data from public functions, you would be able to access it only from private functions, right. However, calling private functions from public functions should consequently also be forbidden, so...

如果您无法从公共函数访问私有数据,那么您只能从私有函数访问它,对吧。但是,因此也应该禁止从公共函数调用私有函数,所以......

How are you supposed to access private data at all?

你应该如何访问私人数据?

回答by mah

Sorry, I'm not watching the video, but I assume you're talking about things like getters (functions to get the value of a property -- a private data member in this case) and setters (functions to set those values).

抱歉,我不是在看视频,但我假设您在谈论 getter(获取属性值的函数——在本例中为私有数据成员)和 setter(设置这些值的函数)之类的东西。

If you provide getters and setters as pure pass-through functions then you're correct, it's really not much different than just making the members public. The normal use though is to provide intelligence into your accessor functions -- letting you, for example, place limits on the values that can be set or letting retrieved values be computed rather than only based on a pure value.

如果您将 getter 和 setter 提供为纯传递函数,那么您是对的,这与仅公开成员实际上没有太大区别。但通常的用途是为您的访问器函数提供智能——例如,让您限制可设置的值或让检索的值被计算,而不仅仅是基于纯值。

回答by ryrich

The purpose with public "getters/setters" if you will, are the fact that they constrain the user from doing more than you want them to. Instead of them getting/setting the private member (in which they can do anything to it), you can limit what they can/can't do by wrapping the private member in a public accessor. That way, inside this public property/function, you can limit the value they can set it too.

如果您愿意,公共“getter/setter”的目的是限制用户做超出您希望的事情。您可以通过将私有成员包装在公共访问器中来限制他们可以/不能做什么,而不是获取/设置私有成员(在其中他们可以对其进行任何操作)。这样,在这个公共属性/函数中,您也可以限制他们可以设置的值。

You can also just have the public property/function get the private member, but prevent the user from setting it.

您也可以让公共属性/函数获取私有成员,但阻止用户设置它。

回答by Coder101101010

Code with getters/setters are considered 'better' than direct private member access because those functions can then control all of the input/output from those variables and make sure it is of the type, range, or whatever that the class expects. It's a way for the class creator to error-check the data being set or manipulate it before returning it.

带有 getter/setter 的代码被认为比直接私有成员访问“更好”,因为这些函数可以控制来自这些变量的所有输入/输出,并确保它是类所期望的类型、范围或任何内容。这是类创建者在返回数据之前对正在设置的数据进行错误检查或操作的一种方式。

If you could just do class.var = value; you could muck things up by putting in the wrong type of variable, or overflowing some limit, or even putting in a legitimate value that some logic in the class's code breaks with. For simple things with a single developer it's usually not a huge issue, but for actual, professional code it's very good practice to encapsulate member variables within a get/set pair for access/writing.

如果你可以只做 class.var = value; 您可能会通过放入错误类型的变量,或溢出某些限制,甚至放入一个合法值而使类代码中的某些逻辑中断,从而使事情变得一团糟。对于单个开发人员的简单事情,这通常不是一个大问题,但对于实际的专业代码,将成员变量封装在 get/set 对中以进行访问/写入是非常好的做法。