Joseph Caruso Joseph Caruso - 7 months ago 73
C++ Question

C++ custom type

I've got a class

, and it is set up in a way that it can essentially be interfaced with as an
(operator overloads), but there's one part I don't get.

int32 i32 = 100; // Works
int i = 200; // Works
i32 += 10; // Works
i32 -= 10; // Works, i32 = 100 right now
i = i32; // Doesn't work

What operator would I need to overload to achieve referencing i32 returning it's stored value, in this case, 100 (or how else could it be done)?


You could add a conversion operator operator int:

class int32 {
    operator int() const;

Note that it comes in two flavours. The above will allow

int32 foo;
int i = foo;

If you define the conversion operator as explicit

    explicit operator int() const;

then the above will fail by design, and require an explicit cast:

int32 foo;
int i = static_cast<int>(foo);