我们知道,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++的封装性,不大好:)