a. 在C++的類的成員函數中,允許直接訪問該類的對象的私有成員變量。
b. 在類的成員函數中可以訪問同類型實例的私有變量。
c. 拷貝構造函數里,可以直接訪問另外一個同類對象(引用)的私有成員。
d. 類的成員函數可以直接訪問作為其參數的同類型對象的私有成員。
舉例:
a.
#include <iostream> using namespace std; class CTest { public: CTest(); CTest(int x); int getX(); void setX(int x); private: int x; }; CTest::CTest(){} CTest::CTest(int x) { this->x = x; } int CTest::getX() { return x; } void CTest::setX(int x) { this->x = x; } int main () { CTest test(100); cout << test.getX() << endl; return 0; }b.
#include <iostream> using namespace std; class A { public: A() { x = 10; } void show() { cout << x << endl; } private: int x; }; class CTest { public: CTest(); CTest(int x); int getX(); void setX(int x); void fun(); private: int x; }; CTest::CTest(){} CTest::CTest(int x) { this->x = x; } int CTest::getX() { return x; } void CTest::setX(int x) { this->x = x; } void CTest::fun() { CTest c; c.x = 100; cout << c.x << endl; //在類的成員函數中不可以訪問非同類型對象的私有變量 /* A a; cout << a.x << endl; */ } int main () { //CTest test(100); //cout << test.getX() << endl; CTest test; test.fun(); return 0; }c.
#include <iostream> using namespace std; class CTest { public: CTest(); CTest(int x); int getX(); void setX(int x); void copy(CTest &test); private: int x; }; CTest::CTest(){} CTest::CTest(int x) { this->x = x; } int CTest::getX() { return x; } void CTest::setX(int x) { this->x = x; } //拷貝構造函數里,可以直接訪問另外一個同類對象(引用)的私有成員 void CTest::copy(CTest &test) { this->x = test.x; } int main () { CTest test(100); CTest a; a.copy(test); cout << a.getX() << endl; return 0; }d.
#include <iostream> using namespace std; class CTest { public: CTest(); CTest(int x); int getX(); void setX(int x); void copy(CTest test); private: int x; }; CTest::CTest(){} CTest::CTest(int x) { this->x = x; } int CTest::getX() { return x; } void CTest::setX(int x) { this->x = x; } //類的成員函數可以直接訪問作為其參數的同類型對象的私有成員 void CTest::copy(CTest test) { this->x = test.x; } int main () { CTest test(100); CTest a; a.copy(test); cout << a.getX() << endl; return 0; }解釋:
私有是為了實現“對外”的信息隱藏,或者說保護,在類自己內部,有必要禁止私有變量的直接訪問嗎?
請記住你是在定義你的類,不是在用。
C++的訪問修飾符的作用是以類為單位,而不是以對象為單位。
通俗的講,同類的對象間可以“互相訪問”對方的數據成員,只不過訪問途徑不是直接訪問.
類體內的訪問沒有訪問限制一說,即private函數可以訪問public/protected/private成員函數或數據成員,同理,protected函數,public函數也可以任意訪問該類體中定義的成員。public繼承下,基類中的public和protected成員繼承為該子類的public和protected成員(成員函數或數據成員),然后訪問仍然按類內的無限制訪問。
每個類的對象都有自己的存貯空間,用於存儲內部變量和類成員;但同一個類的所有對象共享一組類方法,即每種方法只有一個源本。