[英]Call an Operator+ function inside the += operator function in 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!
}
是的,可以,您可以使函數返回一個矩陣:
*this = *this + orig;
return *this;
您可以像在其他地方一樣簡單地調用+運算符。 這里的一個操作數當然是參數orig
而另一個是您自己調用運算符的對象,即*this
。
所以你可以這樣寫:
*this = *this + orig
使用operator+
定義operator+=
是明智的選擇,還是相反,更好的方法是由您決定,這可能取決於您的實現。
但是,通常最好將+ =運算符定義為
Matrix& Matrix::operator+= (const Matrix & orig)
因為你可以做類似的事情
mat += otherMat += otherMat2;
為此,只需返回*this
如Stefan Giapantzakis已經指出的那樣。
這很容易:只需執行*this = *this + other
。
然而,往往是一個更好的主意,寫operator+=
完全, 然后寫operator+
來講+=
這樣的:
Matrix& Matrix::operator+=(const Matrix &rhs) {
try {
if (rows != orig.rows || columns != orig.columns)
throw "Error. Check Matrix dimensions, they do not match.";
} catch (char const* msg) {
std::cout << msg << std::endl;
}
int length = columns * rows;
for (int i = 0; i < length; i++) {
data[i] += orig.data[i];
}
return *this;
}
friend Matrix operator+(Matrix lhs, Matrix const& rhs){
lhs += rhs;
return std::move(lhs);
}
作為獎勵,它可以將a+b+c+d
還原成一個不動的構造矩陣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.