我在下面有这个重载+运算符函数,并且必须编写另一个重载+ =运算符函数。我想知道是否我可以在= +运算符函数中调用+运算符函数,因为基本上这两个函数都在做同样的事情。如果是这样,那么它的语法是什么样子?在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 +'。 –