使用成员变量的偏移量访问结构的私有成员 [英] Accessing private members of a struct using offset of member variables
本文介绍了使用成员变量的偏移量访问结构的私有成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在阅读有关结构和结构填充的内容,并编写了此代码.它使用从 a 的地址偏移量来编辑结构的私有成员.这是否意味着您可以参加某人制作的课程并提取/更改私有变量和函数?
I was reading about structs and struct padding and I wrote this code. It edits a private member of a struct using its address offset from a. Does this mean you can take a class someone made and extract/change private varriables and functions?
#include <iostream>
typedef struct x {
int a;
private:
int b;
public:
//Init
x(int a, int b) : a(a) , b(b){}
void print(){
//Print values
std::cout << a << " " << b << std::endl;
}
} x;
int main()
{
struct x s(10,20) ;
int *p = (int *)(((char*)&s)+4); //4 Byte offset from a (a is at base)
s.print();
(*p) +=1;
s.print();
//Stops terminal closing
int junk;
std::cin >> junk;
return 1;
}
推荐答案
C++ 的 private
用于为抽象数据类型提供封装机制.不是阻止人们编写坏代码,如果他们真的想要.
C++'s private
is for giving abstract data types an encapsulation mechanism. It's not for preventing people from writing bad code if they really want to.
这篇关于使用成员变量的偏移量访问结构的私有成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文