这是C++吗?方法按预期工作吗?

发布于 2024-12-20 20:31:47 字数 1432 浏览 2 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

套路撩心 2024-12-27 20:31:47

你做错的事情是假设它在 << 中起作用表达式按从左到右的顺序求值。他们不一定。在这种情况下,您的编译器将从右到左评估它们。

(澄清一下,由于最初的问题没有说,他看到的行为是打印出来:

1
98
do

相反。(或者至少,这是我的假设,因为这是我用 g++ 编译它时得到的结果)

发生的事情是运算符两侧的表达式都必须在运算符之前运行,但无论出于何种原因,它们都可以按任意顺序运行,在这种情况下,编译器首先运行最右边的 searchValue 调用,然后运行中间的调用。然后是左边由于 searchValue 改变了 s,这当然会改变答案,

您可能认为您编写的代码一定会给出与以下相同的答案:

  string s="< feature token = \"do\" id = \"98\" freq = \"1\" />";
  string x = searchValue(s,'\"');
  string y = searchValue(s,'\"');
  string z = searchValue(s,'\"');
  cout << x << endl << y << endl << z << endl;

但事实并非如此,并且至少在这种特殊情况下,它是这样的。如果您运行该代码,您会看到它给出了预期的结果,就像这样编写的:

  string s="< feature token = \"do\" id = \"98\" freq = \"1\" />";
  string z = searchValue(s,'\"');
  string y = searchValue(s,'\"');
  string x = searchValue(s,'\"');
  cout << x << endl << y << endl << z << endl;

What you're doing wrong is assuming that that functions in a << expression evaluate in left-to-right order. They don't necessarily. And in this case your compiler is evaluating them right to left.

(To clarify, since the original question didn't say, the behavior he's seeing is that it's printing out:

1
98
do

instead. (Or at least, that's what I assume because that's what I get when I compile it with g++)

What's happening is that the expressions on either side of an operator both have to be run before the operator, but they can be run in either order. For whatever reason, in this case, your compiler is running the rightmost call to searchValue first and then the middle one and then the left one. Since searchValue changes s, this, of course, changes the answer.

You might think that the code you wrote is guaranteed to give you the same answer as:

  string s="< feature token = \"do\" id = \"98\" freq = \"1\" />";
  string x = searchValue(s,'\"');
  string y = searchValue(s,'\"');
  string z = searchValue(s,'\"');
  cout << x << endl << y << endl << z << endl;

but it isn't, and, at least in this particular case, it doesn't. If you run that code, you'll see that it gives you the expected result. Your code is running as if it were written like this:

  string s="< feature token = \"do\" id = \"98\" freq = \"1\" />";
  string z = searchValue(s,'\"');
  string y = searchValue(s,'\"');
  string x = searchValue(s,'\"');
  cout << x << endl << y << endl << z << endl;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文