2015-12-29 210 views
-5

這裏例如訪問私人數據成員?

class A { 
    int i; 
} 

void main() 
{ 
    A a; 
} 

一些代碼是否有任何可能的(可能的hackish)方式main訪問a::i

編輯: a::i應該保持私密。

+4

爲什麼要這麼做?無論如何,更好的發佈真正的C++代碼。 – juanchopanza

+4

是'struct A'。 – 101010

+1

只是公開。無論如何,你可以確定'i'與'a'的偏移量,從'a'的地址確定'a.i'的地址,但是你會是個傻瓜。 –

回答

4
*reinterpret_cast<int*>(&a) = 666; 

這應該做的伎倆。

現在,從技術上講,當類型不同時,通過使用post reinterpret_cast變量導致UB。但是,i保證在A的開頭,因爲A是POD。

如果存在虛函數,這絕對不行,如果您有自定義構造函數,則不能保證。

你不應該做任何遠程這樣的事情!

1

可以肯定,這是不能保證的工作,但它會在大多數平臺上可能工作:

#include <iostream> 

class A { 
    int i; 

    public: 
    A (int j) : i(j) { ; } 
}; 

int awfulGetI(A const& a); 

int main() 
{ 
    A a(3); 
    int j = awfulGetI(a); 
    std::cout << "a.i=" << j << std::endl; 
} 

// Ugly code that may or may not work here: 
struct AA { 
    int i; 
}; 

int awfulGetI(A const& a) 
{ 
    struct AA const* p = reinterpret_cast<AA const*>(&a); 
    return p->i; 
} 
0

當創建類,一般的一點是他們提供(儘管的封裝當然,您可能需要檢索或更改其中的值)。總是有可能使用內存地址,正如在這裏的幾個答案中所展示的那樣,但是您是否考慮在您的類中創建一個公共的「getter」函數,該函數只是返回變量的值(因爲函數本身可以訪問) ?

Ex。

class A { 
    // private: 
    int i = 7; 
    // default value used for illustration purposes. 
    // public: 
    public int getInt() 
     { 
     return i; 
     } 
    } 

int main() { 
    A a; 
    int x = a.getInt(); // when called, getInt() should return 7 (in this case). 
    cout << x; // just to check. 
    return 0; 
    }