C++从静态成员函数更改私有成员变量
我在阅读代码时注意到,我有一个静态成员函数,它通过指向该类实例的指针来更改其类的私有成员。
它编译和运行没有问题,但我只是想知道以这种方式从成员静态函数编辑私有变量是否合理,或者我是否应该实现公共 setVar 函数。
请注意,我并不是试图通过编辑静态函数中的成员变量来绕过标准编码实践 - 该函数必须是静态的,以便它可以使用 POSIX pthread 库作为线程运行。
干杯, 怀亚特
I noticed while reading through my code that I have a static member function which alters a private member of its class through a pointer to an instance of said class.
It compiles and functions without issue, but I just wanted to know whether or not it was kosher to edit a private variable in this way, from a member but static function, or if I should be implmenting a public setVar function.
Note that I'm not trying to bypass standard coding practice by editing member variables from a static function - the function is necessarily static so that it can be run as a thread using the POSIX pthread library.
Cheers,
Wyatt
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,这是有效的。
尽管在大多数情况下使用非静态成员更好,但有时在需要将函数指针传递到外部库的情况下使用静态成员,例如 pthread 库的情况。
如果在其他情况下更改此私有变量也有意义,并且如果您想将您的类与它使用 pthread 库的事实分开,您可以将该类分成两部分:
然后第二个类将通过公共方法在第一个类中设置变量。
示例:这可能是您的原始代码:
您也可以这样编写它:
这样,您就可以将您的类与 PThread 库使用它的事实完全分开。它使得它在其他情况下也可用(静态方法毫无意义),并且也很容易添加另一个线程库(例如Windows线程)而不会污染原始类。
Yes, this is valid.
Although having a non-static member is better in most cases, static members are sometimes used in cases where you need to pass a function-pointer to an external library, like in your case for the pthread library.
If it makes sense to change this private variable in other situations as well, and if you want to separate your class from the fact that it uses the pthread library, you could split up the class in two:
The second class will then set the variable in the first class via a public method.
Example: this is probably your original code:
and this is how you could also write it:
That way, you completely separate your class from the fact that it is being used by the PThread library. It makes it usable in other cases as well (where the static-method is rather pointless) and it is also easy to add another thread-library (e.g. Windows threads) without polluting the original class.
是的。
private
表示访问仅限于该类。Yes.
private
means that access is restricted to the class.