Joseph Caruso Joseph Caruso - 2 months ago 6
C++ Question

Custom struct interacted with as if it were an int?

I'm trying to create a structure that can be interacted with as if it were an

int
. However, when I try to assign a value to it, it throws the following error upon compiling:

Invalid conversion from `int` to `int32*`


Why does it throw that error, even though I made it's
=
operator to handle setting an
int32
to a
const int
value?

Here's the source code for my best attempt at
int32
:

struct int32
{
int32_t val;

int32(int val=0)
: val(val)
{
}

int32& operator=(const int value) // ex. int32 *i = 42;
{
val=value;
return *this;
}
int32 operator+(const int32& value) const
{
return int32(value.val+val);
}
int32 operator-(const int32& value) const
{
return int32(value.val-val);
}
int32 operator*(const int32& value) const
{
return int32(value.val*val);
}
int32 operator/(const int32& value) const
{
return int32(value.val/val);
}
int32 operator%(const int32& value) const
{
return int32(value.val%val);
}
bool operator==(const int32& value) const
{
return (val == value.val);
}
bool operator!=(const int32& value) const
{
return (val != value.val);
}
}


Also, please don't just recommend I use
int32_t
; I'm making my own
struct
for a reason (otherwise I'd have just used
int32_t
to begin with ;)

Answer

Judging by your comments, you're doing this:

int32 *i = 42;

You're trying to assign the value 42 to a pointer, which won't work here. Drop the * and call your constructor instead:

int32 i(42);

If you need a pointer to that object, you can then simply take its address:

int32 my_int32(42);
int32 *i = &my_int32;

If you have a pointer to an existing int32 object, and want to assign a new value to the object, you can dereference the pointer:

int32 *i = ...;
*i = 42;
Comments