How to gain Access to member variables of a class using void pointer but Not Object

后端 未结 6 1094
暖寄归人
暖寄归人 2021-01-24 21:29

I am trying to access member variables of a class without using object. please let me know how to go about.

class TestMem
{
    int a;
    int b;
public:
    Tes         


        
6条回答
  •  猫巷女王i
    2021-01-24 22:17

    I wanted to comment the answer provided by John Kugelman, being a new member didn't have enough reputation, hence posting it like an answer.

    offsetof - is a C function used with structures where every member is a public, not sure whether we can refer the private variables as referred in the answer.

    However the same can be achieved replacing the offsetof with a simple sizeof, ofcourse when we are sure of the type of the data members.

    int vala = *reinterpret_cast(reinterpret_cast( ptr ) );
    int valb = *reinterpret_cast(reinterpret_cast( ptr ) + sizeof ( int ) );
    

    To my knowledge, you wouldn't be able to access. By the time you have assigned p, it doesn't refer to o1 here and p cannot replace pMem in (o1.*pMem)(), as p is not defined as function member to TestMem.

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题