[英]C# private variable & java private variable getter & setter - Difference?
[英]What's the difference between a private variable in Java and a private variable in a C++ struct?
Java类中的私有变量和C ++结构中的私有变量有什么区别?
例如,下面的Java代码:实现ADT表。 c ++示例,请参见下面:应用“隐藏实现”
我在网上看找不到与该特定主题相关的有用信息
Java示例:
class Table{
private int size;
private int num;//numbers of items are stored in the arrray
private int[] array;
public Table(int size, int[] array){
this.size = size;
this.array = new int[size];
}
public insert(int[] array, int newItem){
if(num<size){
//for loop for adding items into the array;
}
else if(num>=size){
//increment the size and copy the original array to the new array
}
}
}
隐藏实现的C ++示例:
struct B{
private:
char j;
float f;
public:
int i;
void func();
};
void::func(){
i = 0;
j = '0';
f = 0.0;
};
int main(){
B b;
b.i = i; // legal
b.j = '1'; // illegal
b.f = 1.0; // illegal now
}
在c ++中,我们无法更改私有变量,是因为这些bj ='1'; bf = 1.0; 在main()函数中有两行,这就是为什么? 在Java中,我们也不能更改main()中的私有变量。
谢谢!
除了极少数例外,C ++和Java中的私有变量的工作原理相似。 具体来说, 通常 ,这些变量只能由包含这些变量的类或struct
的成员函数访问。 否则不允许访问这些字段/数据成员。
此规则有两个例外。 非详尽清单:
在Java中,您可以使用反射使其他类的私有字段可访问,尽管访问控制器可能阻止这样做。
在C ++中,私有字段可以由被标记为类和函数访问friend
包含私有字段的类的第
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.