• 关于C++类中的成员


    突然发现,如果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;
    }
  • 相关阅读:
    【leetcode】图像渲染
    【leetcode】不邻接植花
    052-75
    052-74
    052-73
    052-71
    052-70
    052-69
    052-67
    052-66
  • 原文地址:https://www.cnblogs.com/Lyush/p/3376275.html
Copyright © 2020-2023  润新知