簡體   English   中英

從 static 方法訪問 class 的私有成員變量

[英]Accessing private member variables of a class from a static method

我可以使用 object 實例(指向對象的指針)直接訪問下面代碼中顯示的 class 的私有成員變量。 據我了解,私人成員不應該被訪問。 有人可以幫忙解釋這種行為背后的原因嗎?

#include <iostream>

class myClass;
using myClassPtr = std::shared_ptr<myClass>;

class myClass {
public:
    myClass(unsigned int val) : m_val(val) {}
    ~myClass() {}

    static
    myClassPtr create(unsigned int val) {
        myClassPtr objPtr = nullptr;
        objPtr = std::make_shared<myClass>(val);
        if(objPtr) {
            std::cout << objPtr->m_val << std::endl;
        }
        return objPtr;
    }
private:
    unsigned int m_val;
};

int main () {
    myClassPtr objPtr = myClass::create(10);
    return 0;
}

Output

anandkrishnr@anandkrishnr-mbp cpp % g++ static_test.cc -std=c++11 -Wall -Werror
anandkrishnr@anandkrishnr-mbp cpp % ./a.out
10
static myClassPtr create(unsigned int val) {

create()myClass的 static 方法,它是此 class 的成員。 因此,它有權訪問其 class 的所有私有成員和方法。 此權利不僅延伸到它自己的 class 實例,而且延伸到此 class 的任何實例。

據我了解,私人成員不應該被訪問。

...除了他們的 class 的成員。

讓我們為您的 class 創建一個完全沒有意義的復制構造函數,與默認情況下獲得的復制構造函數相同:

myClass(const myClass &o) : m_val{o.m_val} {}

此復制構造函數在訪問傳入的m_val的 m_val 時沒有任何問題。 完全相同的事情發生在這里。 m_val是其 class 的私有成員。 It doesn't mean that only an instance of the same exact object can access its private members, it means that any instance of the class, or a static class method, can access the private class members.

class 上的訪問修飾符的性質是限制在該 class之外使用類的成員。

由於create()myClass中,因此create()可以訪問您聲明的myclass的任何私有成員(或實際上任何成員)。 包括m_val

例如,讓我們做一個簡單的 class,

如果你有代碼:

class box {
private:
    int width;
    int height;
};
int main() {
    box b;
    b.width;

    return 0;
}

編譯器會拋出錯誤: error C2248: 'box::width': cannot access private member declared in class 'box'

Because the main() function is declared outside of the class, therefore, the main() function is not allowed to access private members of the class box .

如果我們想訪問 class 之外的寬度,比如寬度,我們需要將這些成員公開,以允許程序中的其他所有內容看到這些成員:

class box {
private:
    int width;
    int height;
public:
    int pubWidth;
    int pubHeight;
};
int main() {
    box b;
    b.pubWidth;

    return 0;
}

這一次,我們試圖訪問的成員是公共的,( pubWidth ) 允許外部函數、類等訪問這些box成員

Programiz 在我看來,有一篇關於 c++ 中訪問修飾符的好文章,易於理解。 我建議看看。 鏈接在這里

小提示:如果沒有指定,class 中的所有成員都是私有的,除了構造函數、析構函數,也許還有一些我想不出的特殊用例。

希望這能解決問題!

暫無
暫無

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

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