为什么我不能比较 IF 语句中的三个不同值?.CPP

Why cant I compare between three different values in IF statement? CPP

本文关键字:三个 CPP 比较 不能 IF 语句 为什么      更新时间:2023-10-16

假设我有下一个代码示例:

std::string MyString("Michael");
std::cout << (str.find_first_of('=') == str.find_last_of('=') == str.npos);

前面的代码应该给我 1,因为来自 str 成员函数的前两个返回值将是:

4294967295

这也是 npos 的价值。但相反,"0"正在屏幕上打印。

另一件奇怪的事情是,下一个代码:

std::string MyString("Michael");
std::cout << (str.find_first_of('=') == str.find_last_of('=')) << std::endl; 
std::cout << (str.find_last_of('=') == str.npos) << std::endl;

为两个输出打印"1"。

有人可以解释为什么我不能像上面那样比较 3 个值?

你不能像这样链接布尔比较(好吧,你可以,但它并没有像你想象的那样)。它需要是:

std::cout << (str.find_first_of('=') == str.npos && str.find_last_of('=') == str.npos);

即由逻辑 AND 连接的两个比较。

(str.find_first_of('=') == str.find_last_of('=') == str.npos)

这基本上是:

(true == str.npos);

这是false,因此,给你0.

更改

std::cout << (str.find_first_of('=') == str.find_last_of('=') == str.npos); 
// compares the result of a==b with c

std::cout << (str.find_first_of('=') == str.find_last_of('=') &&  str.find_last_of('=') == str.npos); 
// ensures a == b && b == c

另外,您可能自己几乎知道答案(只是试图将事情联系起来)-

std::cout << (str.find_first_of('=') == str.find_last_of('='))

给你1,你当然知道str.npos = 4294967295

简化事情 -

std::cout << (str.find_first_of('=') == str.find_last_of('=') == str.npos)

更改为

std::cout << (1 == 4294967295) 

并导致0.

注意 - 特别是以first_oflast_of比较为例,因为==遵循从左到右的关联性。尽管在您的情况下,无论如何结果都是一样的。