我正在學習C++中的運算符重載。原始後綴++具有比賦值運算符優先級低的屬性。因此,例如,int i=0, j=0; i=j++; cout<<i<<j
將輸出01.但是,當我重載後綴++時,此屬性似乎會丟失。C++運算符重載前綴/後綴
#include<iostream>
using namespace std;
class V
{
public:
int vec[2];
V(int a0, int a1)
{
vec[0]=a0;vec[1]=a1;
}
V operator++(int dummy)
{
for(int i=0; i<2; i++)
{
++vec[i];
}
V v(vec[0],vec[1]);
return v;
}
V operator=(V other)
{
vec[0]=other.vec[0];
vec[1]=other.vec[1];
return *this;
}
void print()
{
cout << "(" << vec[0] << ", " << vec[1] << ")" << endl;
}
};
int main(void)
{
V v1(0,0), v2(1,1);
v1.print();
v1=v2++;
v1.print();
}
輸出(0,0)(2,2)而我期望(0,0)(1,1)。
你能幫助我理解爲什麼是這樣的,並恢復原來的財產的任何可能性?
「原始後綴++的屬性優先於賦值運算符。」除非你是認爲低優先級比高優先級更強的人之一,否則這是錯誤的。後增量的優先級高於賦值的優先級,但後增量返回非增量值。 –
感謝您澄清我的誤解,我用int i = 0,j = 0測試了這個問題; I =(j ++); COUT <<我<<焦耳;它輸出01.所以它不是優先級,而是返回機制。 – focusHard