我在下面有這個重載+運算符函數,並且必須編寫另一個重載+ =運算符函數。我想知道是否我可以在= +運算符函數中調用+運算符函數,因爲基本上這兩個函數都在做同樣的事情。如果是這樣,那麼它的語法是什麼樣子?在C++中調用+ =運算符函數中的運算符+函數
下面是我的+運算符函數。我試圖添加2個動態分配的矩陣。
Matrix Matrix::operator + (const Matrix & orig) const
{
int length = columns * rows;
try
{
if (rows != orig.rows || columns != orig.columns)
{
throw 1;
}
}
catch (int c)
{
if (c == 1)
{
cout << "Error. Check Matrix dimensions, they do not match." << endl;
}
}
Matrix x(rows, columns);
for (int i = 0; i < length; i++)
{
x.data[i] = data[i] + orig.data[i];
}
return x;
}
void Matrix::operator += (const Matrix & orig)
{
//just call the + operator function!
}
1)是的,你可以。 2)你通常會怎麼稱呼操作員+功能? – immibis
這是一個相當無用的try/catch塊,因爲你所做的只是在繼續之前寫入stdout。操作符+和操作符+ =之間存在語義差異,因爲前者返回一個新對象,+ =正在修改它。 –
通常情況下,你可以用相反的方法:寫'operator + =',並根據它定義'operator +'。 –