我正在嘗試使用已編寫的+
運算符函數爲C++類的+=
運算符編寫函數。到目前爲止,我還沒有成功將this
指針與+
運算符關聯起來。這些是我在g++
編制的一些嘗試,但沒有產生期望的結果。我兩次嘗試簡單地製作this
課程的副本,但看起來並不奏效。C++類:在成員函數內創建「this」類的副本
intstr& intstr::operator+=(const intstr& i)
{
intstr *a;
a = new intstr;
*a = *this + i;
return *a;
}
intstr& intstr::operator+=(const intstr& i)
{
intstr *a, b(*this);
a = new intstr;
*a = b + i;
return *a;
}
intstr& intstr::operator+=(const intstr& i)
{
intstr *a, *b;
a = new intstr;
b = this;
*a = *b + i;
return *a;
}
intstr& intstr::operator+=(const intstr& i)
{
intstr *a;
a = new intstr;
*a = this->operator+(i);
return *a;
}
在測試代碼,所有我所做的是a += i
替換代碼a = a + i
工作線,所以我懷疑問題出在那裏,但它是可能的。是否只有這樣才能將代碼從+
運算符複製到+=
函數中?
可能的複製(推薦閱讀反正):http://stackoverflow.com/questions/4421706/operator-overloading – JBentley 2014-10-17 04:27:58