C/C++—— 除了用類成員函式訪問類私有成員變數外,還可以通過類物件地址來直接訪問和修改類的私有成員變數

readyao發表於2016-03-21

除了用類成員函式訪問類私有成員變數外,還可以通過類物件地址來直接訪問和修改類的私有成員變數


/*************************************************************************
	> File Name: visit_private_data.cpp
	> Author: 
	> Mail: 
	> Created Time: 2016年03月21日 星期一 20時10分37秒
 ************************************************************************/

#include <iostream>
#include <string>
using namespace std;

class People{

    private:
        int num;
        int age;
        int hight;
        string name;
    public:
        People(){}
        People(int n, int a, int h, string na):num(n), age(a), hight(h), name(na){}
        ~People(){}

        int get_num(){return num;}
        int get_age(){return age;}
        int get_hight(){return hight;}
        string get_name(){return name;}
        
        void set_num(int val){num = val;}
        void set_age(int val){age = val;}
        void set_hight(int val){hight = val;}
        void set_name(string val){name = val;} 
};

int main()
{
    People p1(1, 22, 170, "linux");
    cout << "p1.num = " << p1.get_num() << endl;
    cout << "p1.age= " << p1.get_age() << endl;
    cout << "p1.hight = " << p1.get_hight() << endl;

    cout << "用地址訪問類的私有成員變數: " << endl;
    int* p = (int*)&p1;
    cout << "*p = " << *p << endl;
    cout << "*(p+1) = " << *(p+1) << endl;
    cout << "*(p+2) = " << *(p+2) << endl;
    
    *p = 11;
    cout << "after *p = 11, *p = " << *p << endl;

    cout << "用地址輸出類物件的前20個位元組的值: " << endl;
    char* ptr = (char*)&p1;

    for(int i = 0; i < 20; ++i){
        cout << "*(ptr+" << i << ") = " << *(ptr+i) << endl;
    }


    return 0;
}

輸出結果:

p1.num = 1
p1.age= 22
p1.hight = 170
用地址訪問類的私有成員變數: 
*p = 1
*(p+1) = 22
*(p+2) = 170
after *p = 11, *p = 11
用地址輸出類物件的前20個位元組的值: 
*(ptr+0) = 

*(ptr+1) = 
*(ptr+2) = 
*(ptr+3) = 
*(ptr+4) = 
*(ptr+5) = 
*(ptr+6) = 
*(ptr+7) = 
*(ptr+8) = (ptr+9) = 
*(ptr+10) = 
*(ptr+11) = 
*(ptr+12) = 
*(ptr+13) = 
*(ptr+14) = 
*(ptr+15) = 
*(ptr+16) = (
*(ptr+17) = (ptr+18) = (ptr+19) = 

可以通過該測試例子得到類的基本成員變數在記憶體中的分佈,但是還不能看到string name成員物件在該People類物件中的分佈。以後肯定還會有其它的書籍會講到。

相關文章