Java 中的私有变量和 C++ 结构中的私有变量有什么区别?

0 c++ java variables struct class

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

}
Run Code Online (Sandbox Code Playgroud)

在 C++ 中我们不能改变私有变量,是不是因为这些 bj = '1'; BF = 1.0; 两行在 main() 函数中,这是为什么?在 java 中,我们也不能更改 main() 中的私有变量。

谢谢你!

tem*_*def 5

除了极少数例外,C++ 和 Java 中的私有变量的工作方式类似。具体来说,一般来说,那些变量只能被类的成员函数或struct包含这些变量的成员函数访问。否则不允许访问这些字段/数据成员。

此规则有几个例外。一个不完全的清单:

  • 在 Java 中,您可以使用反射使其他类的私有字段可访问,但访问控制器可能会阻止这样做。

  • 在 C++ 中,私有字段可以被标记为friend包含私有字段的类的 s 的类和函数访问。