簡體   English   中英

Java中的私有變量和C ++結構中的私有變量有什么區別?

[英]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包含私有字段的類的第

私有變量是在類本身之外不可訪問的變量。

在此處了解有關訪問修飾符的更多信息

structs中的C ++ private structs類似,僅在結構的member methods可以對其進行訪問。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM