gpt4 book ai didi

C++,通过引用变量传递不在调用函数的同一行上更新

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

在我的c++程序中,我有这个函数,

char MostFrequentCharacter(ifstream &ifs, int &numOccurances);

在 main() 中,是这段代码,

ifstream in("file.htm");
int maxOccurances = 0;
cout <<"Most freq char is "<<MostFrequentCharacter(in, maxOccurances)<<" : "<<maxOccurances;

但这不起作用,虽然我得到了正确的字符,但 maxOccurance 仍然为零。但是如果我用这个替换 main 中的上面代码,

ifstream in("file.htm");
int maxOccurances = 0;
char maxFreq = MostFrequentCharacter(in, maxOccurances);
cout <<"Most freq char is "<<maxFreq<<" : "<<maxOccurances;

然后,它就可以正常工作了。我的问题是为什么它在第一种情况下不起作用。

最佳答案

在 C++ 中,

cout << a << b 

通过关联性评估为:

(cout << a) << b 

但编译器可以自由地以任何顺序评估它们。

也就是说,编译器可以评估b首先,然后 a , 然后是第一个 <<操作和第二个<<手术。这是因为没有与 << 关联的序列点


为了简单起见,让我们考虑以下等价的代码:

 #include<iostream>
int main()
{
int i = 0;
std::cout<<i<<i++;
return 0;
}

在上面的源码中:

std::cout<<i<<i++;

计算函数调用:

operator<<(operator<<(std::cout,i),i++);

在这个函数中调用是否operator<<(std::cout,i)i++首先被评估的是 Unspecified. 即:

operator<<(std::cout,i)可能先评估或者
i++可能先评估或者
编译器实现的一些魔法排序

鉴于上述情况,无法定义此顺序,因此也无法解释。


C++03 标准的相关引述:
第 1.9 节

Certain other aspects and operations of the abstract machine are described in this International Standard as unspecified (for example, order of evaluation of arguments to a function). Where possible, this International Standard defines a set of allowable behaviors. These define the nondeterministic aspects of the abstract machine.

关于C++,通过引用变量传递不在调用函数的同一行上更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7006569/

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