F
firstlast1234567890
Hello, I am trying to understand overloaded operators but am getting
confused as to how I can provide a conversion from my number class and
the scalar types?
If I create a class that represents a fictional number type, I
understand that I can create an overloaded assignment operator that
will accept long int for example. What I do not understand is how I
create an assignment operator to do the reverse, i.e. assign my
numeric class value to the scalar long int?
class myLong
{
public:
myLong()
: val(0)
{
};
myLong(long val)
: val(val)
{
};
myLong(const myLong& that)
: val(that.val)
{
};
myLong& operator=(const myLong& that)
{
if (this != &that)
{
this->val = const_cast<myLong&>(that).getVal();
}
return(*this);
};
long getVal()
{
return(val);
};
private:
long val;
};
So this works for something like
myLong mylong;
mylong = 42;
long scalarLong = mylong.getVal();
myLong newLong = mylong;
scalarLong++;
mylong = scalarLong;
But how do I do something like this
myLong myLongTest;
myLongTest = 1;
long scalarLong = myLongTest;
I do not know how to code this reverse assignment. I tried a few ways
but failed dismally.
confused as to how I can provide a conversion from my number class and
the scalar types?
If I create a class that represents a fictional number type, I
understand that I can create an overloaded assignment operator that
will accept long int for example. What I do not understand is how I
create an assignment operator to do the reverse, i.e. assign my
numeric class value to the scalar long int?
class myLong
{
public:
myLong()
: val(0)
{
};
myLong(long val)
: val(val)
{
};
myLong(const myLong& that)
: val(that.val)
{
};
myLong& operator=(const myLong& that)
{
if (this != &that)
{
this->val = const_cast<myLong&>(that).getVal();
}
return(*this);
};
long getVal()
{
return(val);
};
private:
long val;
};
So this works for something like
myLong mylong;
mylong = 42;
long scalarLong = mylong.getVal();
myLong newLong = mylong;
scalarLong++;
mylong = scalarLong;
But how do I do something like this
myLong myLongTest;
myLongTest = 1;
long scalarLong = myLongTest;
I do not know how to code this reverse assignment. I tried a few ways
but failed dismally.