其他成员变量的方法内成员变量的隐私
成员变量的方法是否可以访问同一类中的其他私有成员变量?我想到了一个函子成员变量。
指向私有成员变量的指针可以在类外部取消引用并赋值吗?那么在另一个成员变量的方法中呢?
也许像
class A
{
someClass a,b;
A(){a(&b);}
}
Do the methods of a member variable have access to other private member variables within the same class? I have in mind a functor member variable.
Can a pointer to a private member variable be dereferenced and assigned to, outside of the class? What about in the method of another member variable?
Maybe something like
class A
{
someClass a,b;
A(){a(&b);}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
每当您调用成员变量的方法时,除非其类型是正在定义的类,否则您将无权访问私有成员变量。
如果您(以某种方式)授予对指向成员变量的指针的访问权限,但没有明确指出它是“const”,是的,它可以被取消引用并分配给它。对于其他成员变量的方法,同样的断言仍然成立。
问题编辑后:
在您的示例中,您正在调用一个方法(通过成员变量“a”),提供指向私有成员变量“b”的指针。您正在 A 中访问这两个私有成员变量,这在 C++ 中是完全正确的。
Whenever you are calling the method of a member variable, unless its type is the class being defined, you won't have access to private member variables.
If you give access (somehow) to a pointer to a member variable, without precising that it is "const", yes, it can be dereferenced and assigned to. The same assertion is still true for the methods of other member variables.
AFTER QUESTION HAS BEEN EDITED :
In your example, you are calling a method (through member variable "a"), providing a pointer to private member variable "b". You are accessing these two private member variables in A, which is perfectly correct c++.
至少如果我正确理解你的问题,答案是否定的。例如,这样的代码:
...将无法编译。事实上,
inner
嵌套在outer
内部,没有为outer
的成员函数提供对 private 的任何特殊访问权限内部
的部分。编辑:编辑后,我根本没有看到任何异常 -
A()
是(显然)class A
的成员,其中还包括私有成员a
和b
。private
的定义是它可以被类内部的代码访问(即名称可见),但不能被类外部的代码访问。由于A()
位于类内部,因此a
和b
对它都是可见的。At least if I understand your question correctly, the answer is no. For example, code like this:
...won't compile. The fact that
inner
is nested inside ofouter
does not give member functions ofouter
any special access to the private parts ofinner
.Edit: post-edit, I don't see anything unusual at all --
A()
is (obviously) a member ofclass A
which also includes private membersa
andb
. The definition ofprivate
is that it's accessible (i.e., the name is visible) to code inside the class, but not to code outside the class. SinceA()
is inside the class, botha
andb
are visible to it.