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

后端 未结 6 1090
暖寄归人
暖寄归人 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条回答
  •  孤独总比滥情好
    2021-01-24 22:05

    There totally is a way. C++ has member pointers, pointers relative to an object. They are defined by prefixing T:: to the * on the pointer type, and used by using the ->* or .* member pointer access operators. So yeah, it looks horrible :).

    class T {
        int a, b;
    public:
        typedef int T::* T_mem_ptr_to_int;
    
        static T_mem_ptr_to_int const a_ptr;
        static T_mem_ptr_to_int const b_ptr;
    };
    
    T::T_mem_ptr_to_int const T::a_ptr = &T::a;
    T::T_mem_ptr_to_int const T::b_ptr = &T::b;
    
    int weird_add(T* left, T* right) {
        return left->*T::a_ptr + right->*T::b_ptr;
    }
    

    This is used much more often for member function pointers, which look like Result (T::*ptr_name)(Arg1, Arg2, ...).

提交回复
热议问题