#include <iostream>
class number
{
int value;
public:
number(){value = 0;}
~number(){}
int operator = (const number &obj)
{
return obj.value;
}
number & operator = (const int &integer)
{
value = integer;
return *this;
}
};
int main()
{
number num = 50; //cannot convert from 'int' to 'number'
int integer = num;//cannot convert from 'number' to 'int'
std::cout << integer << "\n";
system("pause");
return 0;
}
operator overloading
I can't get this to work at all but I can't see anything wrong with it :(
Your assignments are actually assignments, they're initializations. In the first one you need a constructor argument that accepts an integer. ex:
For the second one, you need a conversion from number to int. Ex:
number(int i) : value(i) {}
For the second one, you need a conversion from number to int. Ex:
operator int() { return value; }
number num = 50; //cannot convert from 'int' to 'number'
This does not mean "make a number called 'num', and then assign 50 to it with the assignment operator". It means "make a number called 'num', passing 50 to a constructor which accepts one argument". It is exactly equivalent to "number num(50);". This is a special case: writing the '=' on the same line that you declare the variable asks for an initialization, not an assignment. These are different things.
Meanwhile, you cannot define the operation "assign an int from a user-defined class". That operator would have to belong to the int class, but int isn't a class, and even if it were, you wouldn't be able to modify it. Instead, you define the operation "interpret myself as an int". This is done like - well, like SiCrane said.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement