How to print function pointers with cout?

前端 未结 7 2515
挽巷
挽巷 2020-11-22 07:09

I want to print out a function pointer using cout, and found it did not work. But it worked after I converting the function pointer to (void *), so does printf with %p, such

7条回答
  •  迷失自我
    2020-11-22 07:09

    Regarding your edit, you can print out contents of anything by accessing it via unsigned char pointer. An example for pointers to member functions:

    #include 
    #include 
    
    struct foo { virtual void bar(){} };
    struct foo2 { };
    struct foo3 : foo2, foo { virtual void bar(){} };
    
    int main()
    {
        void (foo3::*p)() = &foo::bar;
    
        unsigned char const * first = reinterpret_cast(&p);
        unsigned char const * last = reinterpret_cast(&p + 1);
    
        for (; first != last; ++first)
        {
            std::cout << std::hex << std::setw(2) << std::setfill('0')
                << (int)*first << ' ';
        }
        std::cout << std::endl;
    }
    

提交回复
热议问题