C++ Overloading Conversion Operators

前端 未结 4 1314
暗喜
暗喜 2021-02-16 00:11

I am trying to have a class that allows implicit casting to certain built in types, like unsigned long int and since I\'m trying to do this as correct as possible (this is my fi

相关标签:
4条回答
  • 2021-02-16 00:22

    The function signature does not match the function definition.

    operator unsigned long int () const;
    

    and

    CustomizedInt::operator unsigned long()    { ... }
                                           ^^^
                                       const missing
    

    In this case you should mark the conversion operator as const since it doesn't affect the internal state of the object.

    Also, use constructor initialization lists to initialize your member variables.

    CustomizedInt::CustomizedInt()
    : data()
    {
    }
    
    CustomizedInt::CustomizedInt(int input)
    : data(input)
    {
    }
    
    0 讨论(0)
  • Yes, if your member function doesn't affect the logical state of the object, then you should indeed postfix it with const, so that the compiler will enforce that.

    But in that case, you also need to add const when you define the function body!

    0 讨论(0)
  • 2021-02-16 00:43

    You just need to copy the same function prototype into the implementation. ie.

    CustomizedInt::operator unsigned long int() const
    
    0 讨论(0)
  • 2021-02-16 00:45

    You could remove the const from the declaration, but what you almost certainly want to do is add it to the definition:

    CustomizedInt::operator unsigned long() const
    {
        unsigned long int output;
        output = (unsigned long int)data;
        return output;
    }
    
    0 讨论(0)
提交回复
热议问题