operator+ and operator= overloading

Started by
3 comments, last by jouley 17 years ago
I'm trying to make one of my classes behave as one would expect them to with these operators, but I'm not sure what I'm doing is working...so I thought I'd post my functions and see if anyone thought they were clearly wrong for some reason.

cOdds cOdds::operator+(const cOdds &c)
{
	wins = wins + c.wins;
	losses = losses + c.losses;
	ties = ties + c.ties;
	hands = hands + c.hands;	
}

cOdds cOdds::operator=(const cOdds &c)
{
	wins = c.wins;
	losses = c.losses;
	ties = c.ties;
	hands = c.hands;
}

I'm under the impression that the "this" operator is implicit, and that I needn't "return" anything in either function, because they are constructors...I think? I'm confused =) Thank you for your time.
Advertisement
Your operator+ looks like it's behaving more like an operator+=

And both of these should return references to *this.

cOdds & cOdds::operator+=(const cOdds & c){    ...    return *this;}cOdds & cOdds::operator=(const cOdds & c){    ...    return *this;    }cOdds operator+(const cOdds & lhs, const cOdds & rhs){    return cOdds(...);}
I've made the modifications you suggested to my operator=, however when I make those modifications to operator+ I get:

main.cc:746: error: ‘cOdds cOdds::operator+(const cOdds&, const cOdds&)’ must take either zero or one argument

Possibily your definition for operator+= is intended for operator+?
Ooops, my bad. That operator+ should be non-member, non-friend. I'll fix it.
Out of curiosity, did these snippets compile with no whining about "'cOdds::operator+' must return a value." ? As it is, they most definitely need to. The first implementation would be more indicative of the '+=' operator. (The left hand cOdds becomes itself "+" the right hand cOdds, which would make use of the implicit "this" pointer. It still needs to return the final result, though, to be consistent with built-in type standards)

What you're looking for, I think, is something like this, depending on how your constructors are set up:
cOdds cOdds::operator +(const cOdds& rhs){	cOdds ret;	ret.m_nLosses = m_nLosses + rhs.m_nLosses;	ret.m_nWins = m_nWins + rhs.m_nWins;	return ret;}cOdds cOdds::operator =(const cOdds& rhs){	m_nLosses = rhs.m_nLosses;	m_nWins = rhs.m_nWins;	return *this;}

Overloaded constructors could make them much simpler, even one-liners, but that's the gist. From there and what you've started on, you should be able to give these and the "+=" a solid go.

Hope this helps!
-jouley

[Edit: Oh-so-beaten.]

This topic is closed to new replies.

Advertisement