我几天前遇到了一个小问题,关于IT技术方面的内容。我向我的朋友在面试中询问了这个问题。
最初的面试问题是:“以下代码的输出结果是什么?”
int i = 2;
i = i++ + i++;
正确答案是 ((2 + 2) + 1) + 1 = 6,也就是说,在加法操作后执行两次后缀递增,然后再赋值。
接下来,我想创建一个简单的类,包含一个整数,并重载 operator+() 和 operator++(int),以便在日志中查看运算符执行的确切顺序。
以下是代码:
class A
{
public:
A(int _data) : data(_data) { }
A &operator=(const A& _rhs)
{
data = _rhs.data;
cout<<" -- assign: "<<data<<endl;
}
A operator++(int _unused)
{
A _tmp = data;
data++;
cout<<" -- post-increment: "<<data<<endl;
return _tmp;
}
A operator+(const A &_rhs)
{
A _tmp = data + _rhs.data;
cout<<" -- addition: "<<data<<"+"<<_rhs.data<<endl;
return _tmp;
}
inline operator int() const { return data; }
private:
int data;
};
结果非常令人沮丧:
-- post-increment: 3
-- post-increment: 4
-- addition: 3+2
-- assign: 5
对于较简单的构造,比如(A _dt2 = a++;),它的作用与预期一致,但运算符的执行顺序并不像整型那样。
我猜这可能是编译器特定的问题:
$ gcc --version
gcc (Ubuntu 4.4.3-4ubuntu5) 4.4.3
Copyright (C) 2009 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
所以,我有点迷惑 :)