欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > c/c++ >内容正文

c/c++

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

发布时间:2025/3/15 c/c++ 27 豆豆
生活随笔 收集整理的这篇文章主要介绍了 C++中直接存取类私有成员[360度] 小编觉得挺不错的,现在分享给大家,帮大家做个参考.
本文谈到的问题是,在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的内容已经修改了。不过通过指针强行访问类的私有成员确实有点那个,嘿嘿。

总结

以上是生活随笔为你收集整理的C++中直接存取类私有成员[360度]的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。