Overload dereference operator

前端 未结 3 1696
醉梦人生
醉梦人生 2021-02-08 20:27

I\'m trying to overload the dereference operator, but compiling the following code results in the error \'initializing\' : cannot convert from \'X\' to \'int\':

相关标签:
3条回答
  • 2021-02-08 21:00

    You should apply dereference operator to a class type. In your code x has a pointer type. Write the following:

    int t = **x;
    

    or

    int t = x->operator*();
    
    0 讨论(0)
  • 2021-02-08 21:10

    You're dereferencing a pointer to X. Your class is OK (as far as it's implemented).

    int main()
    {
        X x; // no pointer
        int t = *x; // x acts like a pointer
    }
    
    0 讨论(0)
  • 2021-02-08 21:13

    If you want the original code to work, you need to overload the int-cast operator for your class:

    operator int() const { return 5; }
    
    0 讨论(0)
提交回复
热议问题