Sign in to follow this  
Sync Views

operator overloading

Recommended Posts

I can't get this to work at all but I can't see anything wrong with it :(
#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;
}

Share this post


Link to post
Share on other sites
Your assignments are actually assignments, they're initializations. In the first one you need a constructor argument that accepts an integer. ex:

number(int i) : value(i) {}

For the second one, you need a conversion from number to int. Ex:

operator int() { return value; }

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this