0
我curently學習有關運算符重載,我發現這個例子:操作符重載例如不明確
#include <iostream>
using namespace std;
class MinMax
{
private:
int m_nMin; // The min value seen so far
int m_nMax; // The max value seen so far
public:
MinMax(int nMin, int nMax)
{
m_nMin = nMin;
m_nMax = nMax;
}
int GetMin() { return m_nMin; }
int GetMax() { return m_nMax; }
friend MinMax operator+(const MinMax &cM1, const MinMax &cM2);
friend MinMax operator+(const MinMax &cM, int nValue);
friend MinMax operator+(int nValue, const MinMax &cM);
};
MinMax operator+(const MinMax &cM1, const MinMax &cM2)
{
// Get the minimum value seen in cM1 and cM2
int nMin = cM1.m_nMin < cM2.m_nMin ? cM1.m_nMin : cM2.m_nMin;
// Get the maximum value seen in cM1 and cM2
int nMax = cM1.m_nMax > cM2.m_nMax ? cM1.m_nMax : cM2.m_nMax;
return MinMax(nMin, nMax);
}
MinMax operator+(const MinMax &cM, int nValue)
{
// Get the minimum value seen in cM and nValue
int nMin = cM.m_nMin < nValue ? cM.m_nMin : nValue;
// Get the maximum value seen in cM and nValue
int nMax = cM.m_nMax > nValue ? cM.m_nMax : nValue;
return MinMax(nMin, nMax);
}
MinMax operator+(int nValue, const MinMax &cM)
{
// call operator+(MinMax, nValue)
return (cM + nValue);
}
int main()
{
MinMax cM1(10, 15);
MinMax cM2(8, 11);
MinMax cM3(3, 12);
MinMax cMFinal = cM1 + cM2 + 5 + 8 + cM3 + 16;
cout << "Result: (" << cMFinal.GetMin() << ", " <<
cMFinal.GetMax() << ")" << endl;
return 0;
}
我不明白怎麼做行MinMax cMFinal = cM1 + cM2 + 5 + 8 + cM3 + 16;
工作。
當計算它時,它變成MinMax cMFinal = MinMax(3, 16)
。接下來發生了什麼?當我沒有定義重載分配操作符時,編譯器如何將一個對象分配給另一個對象?
複製elison會發生在這裏,不是嗎?如果它不會移動構造函數而不是複製構造函數? – 0x499602D2
@ 0x499602D2是會發生copy-elision,但我會將其另存爲另一個問題(當OP詢問爲什麼他/她自己的複製構造函數未被調用時)。 :) –