Sign in to follow this  

Problem overloading - operator

This topic is 1709 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I want to be able to write an expression like: a+b-c + and - will be overloaded

 

Here;s my class:

 

class go{
	
public:
	int i;
	const go operator++(int){
		go before;
		before.i = this->i;
		i++;
		return before;
	}

	const go operator+(go& m){
		go x;
		x.i= this->i + m.i;
		return x;

	}

	const go operator-(go& m){
		go x;
		x.i = i - m.i;
		return x;
	}

	void print(ostream& e){
		e << this->i << endl;

	}
};

 

 

If I create 3 objects of type go,initialize all of them,and do the above expression,a+b-c,on - it will show an error like:

no operator - matches these operands.

 

What is wrong?

 

 

 

Solved: define the operator overloaded functions as global,but make them a friend to the class.That way,you can get your hands on both operands!

Edited by noatom

Share this post


Link to post
Share on other sites

Solved: define the operator overloaded functions as global,but make them a friend to the class.That way,you can get your hands on both operands!

There are sometimes valid reasons for friend functions instead of member function. Not understanding essential and basic things like constness and parameter passing is not one of them though. Sorry for sounding blunt, but you really need a lot of more knowledge and experience before you should decide to do a "Solved" in obnoxious font sizes.

Share this post


Link to post
Share on other sites

Solved: define the operator overloaded functions as global,but make them a friend to the class.That way,you can get your hands on both operands!


Like has been said, this may have "solved" it but I would not call it proper and a hacked solution.

The proper solution for what you want was posted the first and second response. I would edit your post just so other people maybe having same problem don't think that is the proper solution.

Share this post


Link to post
Share on other sites

This topic is 1709 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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