C++クラスのメンバーについて
4328 ワード
突然、C++のクラスメンバーに共通のメンバーが存在する場合、ポインタのオフセットによってプライベートなメンバー変数にアクセスできます.もちろん、メモリの位置合わせが明確であることが前提です.コンパイラを騙すだけでやりたい放題です.
----------------------------------------------------
オブジェクトのアドレスを直接取得し、すべてのプライベートメンバーにアクセスできます.
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
using namespace std;
struct Node {
private:
double a;
char b;
public:
void display() {
printf("%p %p %p
", &a, &b, &c);
}
int c;
Node() : a(1000.0), b('b'), c(3) {}
};
int main() {
Node x;
x.display();
int *p = &x.c;
printf("%d %c %lf
", *p, *((char *)(p)-4), *(double *)((char *)p-12));
return 0;
}
----------------------------------------------------
オブジェクトのアドレスを直接取得し、すべてのプライベートメンバーにアクセスできます.
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <iostream>
using namespace std;
class Node {
private:
int a, b;
public:
Node(int _a, int _b) : a(_a), b(_b) {}
};
int main() {
Node A(2, 3);
int *p = (int *)&A;
printf("%d %d
", *p, *(p+1));
return 0;
}