我們知道,C++的類是有封裝性的,那麼對於私有數據成員我們如果想在類外訪問,一般而言無外乎這麼兩種方法:
1、通過公有的成員函數
2、通過友元
這是兩種通常的做法,還有一種是比較“反常”的,但是同樣也可以達到這樣的目的,那就是通過類的基地址偏移來訪問,這是網上有人給出的例程:
#include <iostream>
#include "conio.h"
class tester
{
public:
tester() : i(5), ch('x'){};
private:
int i;
char ch;
};
int main(void)
{
tester myTester;
char* p = NULL;
p = (char*) &myTester + sizeof(int); //Here is the point! Jumps sizeof(int) units of bytes!
cout << "Address of ch = " << (void*) p << endl; //The type modifier void* forces it to output the
//address, not the content.
cout << "ch = " << * (p) << endl;
getch(); //Waits your action
* p = 'y';
cout << "Now ch = " << * (p) << endl;
return 0;
}
真是不看不知道,原來還可以這樣子,指針這個東西還真是……。不過這種反常的做法也受到了一些限制,比方說對類的內存佈局你需要清楚,否則得不到正確的地址。實際當中真的不知道誰是這麼用的,總之是破壞了C++的封裝性,不大好:)