2015-07-12 65 views
1

我想知道我能夠訪問通過引用或值傳遞的對象的私有數據嗎?此代碼有效。爲什麼?我需要一些解釋。如何訪問通過引用operator = function傳遞的對象的私有數據?

class test_t { 
    int data; 
public: 
    test_t(int val = 1): data(val){} 
    test_t& operator=(const test_t &); 
}; 

test_t& test_t::operator=(const test_t & o){ 
    this->data = o.data; 
    return *this; 
} 
+0

這只是一個規則 – kiviak

+1

@kiviak謝謝船長明顯。 – emlai

+0

請參閱http://stackoverflow.com/questions/6921185/why-do-objects-of-the-same-class-have-access-to-each-others-private-data –

回答

6

privatetest_t類的所有實例可以看到對方的私人數據。

如果C++是更嚴格,並限制private訪問相同的實例中的方法,這將是有效的話說,*this類型是「更強大」比你o引用的類型。

類型的*this是相同的(†)作爲o類型,即test_t &,因此可以o做任何*this可以做到的。

(†)除了const之外,還有相同的類型,但在這裏並不重要。

+3

從語義上講,'private'意味着它是類實現的一部分,只能通過類的實現來訪問。 –