C++中直接存取类私有成员[360度]

王朝c/c++·作者佚名  2006-02-04
窄屏简体版  字體: |||超大  

本文谈到的问题是,在C++中究竟有没有办法访问类的私有成员,以及如何实现。主要针对菜鸟,老鸟们就不要看了。

读到《C++编程思想》48页,“3.4 对象布局”一节时,看到这样一段话:

存取指定符是struct的一部分,他并不影响这个struct产生的对象,程序开始运行时,所有的存取指定信息都消失了。存取指定信息通常是在编译期间消失的。在程序运行期间,对象变成了一个存储区域,别无他物,因此,如果有人真的想破坏这些规则并且直接存取内存中的数据,就如在C中所做的那样,那么C++并不能防止他做这种不明智的事,它只是提供给人们一个更容易、更方便的方法。

既然是在编译期间去掉了所有的存取限制属性,那么能不能设计一段代码绕过编译器的检查机制,又能在运行期间访问类的私有成员呢? 首先想到了条件转移语句——编译器对条件转移代码块的编译是否有可利用之处呢?虽然实验失败了,但我的第一想法确实是这个。示例代码如下:

//tester.h

//Demo class

class tester

{

public:

tester() : i(5), ch('x'){};

private:

int i;

char ch;

};

//test1.cpp

//Demo testing code

#include "tester.h"

#include<conio.h>

#include<iostream>

using namespace std;

void main(void)

{

tester myTester;

char* p = NULL;

if (1 > 0)

{

p = &myTester.ch; //Here is the point

}

cout << "Address of ch = " << (void*) p << endl; //The type modifier void* forces it to output the

//address, not its content

cout << "ch = " << * (p) << endl;

getch(); //Waits your action

* p = 'y';

cout << "Now ch = " << * (p) << endl;

}

结果正如上面所说,失败了:编译器报错:error C2248: 'ch' : cannot access private member declared in class 'tester'。不过这引发了更深一步的思考。C语言里面最活的就是指针了,平常最怕乱指的野指针,这一次就试试它!修改后的测试代码如下:

//test2.cpp

//Demo testing code

#include "tester.h"

#include<conio.h>

#include<iostream>

using namespace std;

void 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;

}

查看输出后可以发现,ch的内容已经修改了。不过通过指针强行访问类的私有成员确实有点那个,嘿嘿。

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航