其他成员变量的方法内成员变量的隐私

发布于 2024-09-14 22:56:37 字数 182 浏览 4 评论 0原文

成员变量的方法是否可以访问同一类中的其他私有成员变量?我想到了一个函子成员变量。

指向私有成员变量的指针可以在类外部取消引用并赋值吗?那么在另一个成员变量的方法中呢?

也许像

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

星星的轨迹 2024-09-21 22:56:37

每当您调用成员变量的方法时,除非其类型是正在定义的类,否则您将无权访问私有成员变量。

如果您(以某种方式)授予对指向成员变量的指针的访问权限,但没有明确指出它是“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++.

那伤。 2024-09-21 22:56:37

至少如果我正确理解你的问题,答案是否定的。例如,这样的代码:

class outer { 
    class inner { 
        int x;
    };

    void use_x() { inner::x = 0; }
};

...将无法编译。事实上,inner 嵌套在 outer 内部,没有outer 的成员函数提供对 private 的任何特殊访问权限内部的部分。

编辑:编辑后,我根本没有看到任何异常 - A() 是(显然)class A 的成员,其中还包括私有成员abprivate 的定义是它可以被类内部的代码访问(即名称可见),但不能被类外部的代码访问。由于 A() 位于类内部,因此 ab 对它都是可见的。

At least if I understand your question correctly, the answer is no. For example, code like this:

class outer { 
    class inner { 
        int x;
    };

    void use_x() { inner::x = 0; }
};

...won't compile. The fact that inner is nested inside of outer does not give member functions of outer any special access to the private parts of inner.

Edit: post-edit, I don't see anything unusual at all -- A() is (obviously) a member of class A which also includes private members a and b. The definition of private is that it's accessible (i.e., the name is visible) to code inside the class, but not to code outside the class. Since A() is inside the class, both a and b are visible to it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文