c++特殊方法可见性
我有一个简单的对象,类型为“ObjectX”,有一个名为“doSomething()”的简单方法。我想让 doSomething 只能被其他 ObjectX 访问。换句话说,如果某个静态对象或不是“ObjectX”类型的对象尝试调用 doSomething,它将无法调用。但是,如果 ObjectX 类型的对象尝试调用该方法,它将能够调用。
这与私有方法不同,私有方法只能从它所在的同一个对象中调用。如果有另一个相同类型的对象在不同的对象上调用该方法,它将被锁定。
I have a simple object, of type "ObjectX", with a simple method called "doSomething()". I'd like to make doSomething ONLY accessable by other ObjectX's. In other words, if something that is either static, or not an object of type "ObjectX" tries to call doSomething, it will be unable to. However, if an object of type ObjectX tries to call the method, it WILL be able to.
This differs from a private method, in that, a private method can only be called from the same object it is in. If there were another object of the same type calling that method on a different object, it would be locked out.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
private
几乎完全符合您的要求。只有相同类型的对象才能使用私有方法,其他对象可以在其他对象上调用这些函数(即私有函数不限于调用对象)。唯一与您描述的不同的是,同一类中的
static
函数也可以使用private
函数。没有任何语言功能可以让您将函数仅限于对象(不包括静态
函数)。private
does almost exactly what you want. Only objects of the same type can useprivate
methods, and other objects can call those functions on other objects (that is,private
functions are not restricted to the invoking object).The only thing that is not as you described is that that
static
functions in the same class can also useprivate
functions. There is no language feature that lets you restrict a function to the object only (excludingstatic
functions).我不知道你从哪里得到你的事实。私有函数
A::foo
可以由任何A
类型的对象调用。无论是在其本身还是在另一个实例上。I don't know where you get your facts. A private function
A::foo
can be called by any object of typeA
. Be it on itself or on another instance.在 C++ 中,
上面的代码可以工作。这就是复制构造函数工作的原因。
上面无论如何都行不通。
如果您还想提供对 B 的访问,请通过在 A 类中指定
friend B;
使 A 成为 B 的好友。In C++
The above code would work.And this is the reason copy constructor work.
Above would not anyways work.
If you want to provide access to B as well make A a friend of B by specifying
friend B;
in class A.