gpt4 book ai didi

c++ - 链接 operator<< 和 operator++ 的问题

转载 作者:太空宇宙 更新时间:2023-11-04 12:33:01 24 4
gpt4 key购买 nike

我正在学习 C++,我遇到了这个问题:

#include <iostream>
using namespace std;


class test
{
public:
test(){};
test(int i):var{i}{};

test& operator++(){++var; return this;}
test operator++(int dummy){test tmp =*this;var++;return tmp;}

friend ostream& operator<<(ostream&, const test&);


private:
int var;
};

ostream& operator<<(ostream& o, const test& obj)
{
o<<obj.var;
return o;
}


int main()
{
test obj{2};
cout << obj << endl;
obj++;
cout << obj << endl;
cout << obj <<' '<< ++obj<<endl;

return 0;
}

我期望的输出是:2个3个3 4

相反,我有:2个3个4 4

如果我用 obj++ 替换最后一个增量++obj ,情况就更奇怪了:2个3个4 3

好像流是反着读的,你能帮帮我吗?

最佳答案

让我们检查一下这条线

cout << obj << ' ' << ++obj << endl;

已翻译。

第一步。

cout << obj

成为

// A non-member function.
operator<<(cout, obj)

第 2 步。

operator<<(cout, obj) << ' '

成为

// Also a non-member function.
operator<<(operator<<(cout, obj), ' ')

第 3 步。

operator<<(operator<<(cout, obj), ' ') << ++obj

成为

// Also a non-member function.
operator<<(operator<<(operator<<(cout, obj), ' '), ++obj)

第 4 步。

operator<<(operator<<(operator<<(cout, obj), ' '), ++obj) << endl;

成为

// A member function.
operator<<(operator<<(operator<<(cout, obj), ' '), ++obj).operator<<(endl);

这是整行。

在这样的表达式中,不能保证 operator<<(cout, obj)将在 ++obj 之前执行.看来在您的平台中,++objoperator<<(cout, obj) 之前执行被执行。这解释了这种行为。

请注意,标准已更改。如果您能够使用 C++17,您将获得预期的行为。

关于c++ - 链接 operator<< 和 operator++ 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57882588/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com