负号重载时的问题
我在写超大整数类HugeInt。在重载单目运算符 - (负号)时遇到点问题
- C/C++ code
HugeInt &HugeInt::operator++ (){ *this=*this+HugeInt(1);//+号已重载,且无问题 return *this;}HugeInt &HugeInt::operator-- (){ *this=*this-HugeInt(1); return *this;}HugeInt HugeInt::operator++ (int){ HugeInt ret(*this); *this=*this+HugeInt(1); return ret;}HugeInt HugeInt::operator-- (int){ HugeInt ret(*this); *this=*this-HugeInt(1); return ret;}HugeInt HugeInt::operator- () const{ HugeInt temp(*this); temp.sign=!sign; // sign 是标志HugeInt正负的bool private变量 return temp;}
这是重载自加、自减、负号的源代码。
但是以下两段main函数中的测试代码结果不同,很诡异
- C/C++ code
HugeInt hi=1; //赋值号已重载,且无问题cout<<hi++<<endl<<hi<<endl<<-hi<<endl;
输出结果为:
1
2
-1 (注意是-1!!!正常结果应是-2!!!)
- C/C++ code
HugeInt hi=1;cout<<hi++<<endl;cout<<hi<<endl;cout<<-hi<<endl;
输出结果为:
1
2
-2 (此结果正常!!!)
这是什么原因引起的?如何修正?
诚心求教,不胜感激
[解决办法]
典型的未定义行为。
参考下面链接中的文章:
C,C++表达式求值顺序 裘老的解释
[解决办法]
你的程序没有问题吧
你即使用 标准类型int,运行出来也是相同结果吧
具体理由比较复杂,
就是一个语句中 对同一个变量进行操作,其操作顺序是不能确定的。
[解决办法]
cout<<hi++<<endl<<hi<<endl<<-hi<<endl;
这是一个完整的表达式,这样写结果是不确定