C ++ - 就像Java中的友元类机制一样 [英] C++-like friend class mechanism in Java
问题描述
你知道我怎样才能在一个特殊的类中改变一个对象?
在这个例子中,我希望对象PrivateObject只能在 Box
类中进行可更改(可递增),而不是其他任何地方。有没有办法实现这个目标?
Do you know how can I make an object changeable only inside a special class?
In this example I want the object PrivateObject to be only changable (incrementable) inside the Box
class, nowhere else. Is there a way to achieve this?
public class Box {
private PrivateObject prv;
public void setPrivateObject(PrivateObject p){
prv = p;
}
public void changeValue(){
prv.increment();
}
}
public class PrivateObject {
private value;
public increment(){
value++;
}
}
PrivateObject priv = new PrivateObject ();
Box box = new Box();
box.setPPrivateObject(priv);
box.changevalue();
priv.increment(); // I don't want it to be changeable outside the Box class!
在C ++中,我会生成所有 PrivateObject
属性和方法private,并声明 Box
类作为 PrivateObject
类的朋友。
In C++, I would make all the PrivateObject
properties and methods private, and the declare the Box
class as a friend for the PrivateObject
class.
推荐答案
如果 PrivateObject
与密切相关Box
为什么不把它作为 Box
中的内部类?
If PrivateObject
is strongly related to Box
why not make it an inner class inside Box
?
class Box {
public static class PrivateObject {
private value;
private increment(){
value++;
}
}
private PrivateObject prv;
public void setPrivateObject(PrivateObject p){
prv = p;
}
public void changeValue(){
prv.increment();
}
}
现在你不能调用增量
来自外部 Box
:
Now you cannot call increment
from outside Box
:
public static void main(String args[]) {
Box.PrivateObject obj = new Box.PrivateObject();
Box b = new Box();
b.setPrivateObject(obj);
obj.increment(); // not visible
}
这篇关于C ++ - 就像Java中的友元类机制一样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!