Why does operator+= only have one parameter?

Here is an example I was given of a different type of code with the operator+= :

1
2
3
4
5
6
7
8
9
10
11
12
String& String:: operator+= (const String& s)
{
	int newlen = strlen(info_) + strlen(s.info_) + 1;

	char* temp = new char[newlen]; // Create new array for combined strings.
	strcpy_s(temp, newlen, info_); // Copy characters from this array into temp.
	strcat_s(temp, newlen, s.info_); // Append characters of s.info_ onto temp.

	delete [] info_; // Replace the old value for info_ by temp.
	info_ = temp;
	return *this;
}


Now I need to code my own operator+= method for a different kind of class but I am confused as to why it only gets one parameter. doing operator+ made sense to me because I just had to find a way to get x + y to work. I guess I am not sure what I am even trying to do with operator+= though. Here is an outline of the function I am working on:

1
2
3
4
	LongInt& LongInt::operator+=(const LongInt& rhs)
	{
		
	}


Thank you for your time in reading this.

I solved it and here is what I came up with:

1
2
3
4
5
6
7
8
9
	LongInt& LongInt::operator+=(const LongInt& rhs)
	{
		LongInt temp;
		temp = *this;
		temp = temp + rhs;
		*this = temp;

		return *this;
	}


This link helped me a lot in understanding what it was I was trying to do :P
http://courses.cms.caltech.edu/cs11/material/cpp/donnie/cpp-ops.html
Last edited on
I'm not sure, but it sounds like you answered your own question. Is that true? Or did you still need clarification?


Anyway, there's no need to create a temporary variable. That just makes your code a little longer and more confusing. Just modify 'this' directly:

1
2
3
4
5
	LongInt& LongInt::operator+=(const LongInt& rhs)
	{
		*this = *this + rhs;
		return *this;
	}
Topic archived. No new replies allowed.