【发布时间】:2016-03-29 02:16:46
【问题描述】:
我有这段代码,但我不明白输出...
class Complex
{
private:
float re;
float im;
public:
Complex(float r = 0.0, float i = 0.0) : re(r), im(i){};
void Print(){cout << "Re=" << re <<",Im=" << im << endl;}
Complex operator++(); //prefiksna
Complex operator++(int); //postfiksna
};
Complex Complex ::operator++()
{
//First, re and im are incremented
//then a local object is created.
return Complex( ++re, ++im);
}
Complex Complex ::operator++(int k)
{
//First a local object is created
//Then re and im are incremented. WHY is this ??????
return Complex( re++, im++);
}
int main()
{
Complex c1(1.0,2.0), c2;
cout << "c1="; c1.Print();
c2 = c1++;
cout << "c2="; c2.Print();
cout << "c1="; c1.Print();
c2 = ++c1;
cout << "c2="; c2.Print();
cout << "c1="; c1.Print();
return 0;
}
输出是:
1. c1=Re=1,Im=2
2。 c2=Re=1,Im=2
3。 c1=Re=2,Im=3
4. c2=Re=3,Im=4
5. c1=Re=3,Im=4
有人可以解释这些输出吗? (1. 是微不足道的,我想我理解 3. 和 5.,只是想确保......)我对 2. 和 4. 的区别非常感兴趣,主要是,不清楚为什么会这样。 .cmets中的代码里面还有一个问题(WHY is this ??????)
【问题讨论】:
-
为复数定义递增/递减运算符,或者将其用作运算符重载的示例,这确实是一个坏主意。那是在我们开始实施之前。
标签: c++ oop operator-overloading operators