我想知道两个结果为何不同?
代码是?
string s1="35",s2="255";
cout<<(s1>s2)<<" "<<("35">"255")<<endl;
Run Code Online (Sandbox Code Playgroud)
输出为:
1 0
C ++中的文字字符串实际上是常量字符的数组。与其他数组一样,它们衰减到指向第一个元素的指针。
与"35">"255"您比较指针,而不是字符串本身的内容。
要比较文字字符串,您需要使用std::strcmp。但是请注意,它不会返回布尔值。
您目前的工作大致相当于
char const* a = "35";
char const* b = "255";
std::cout << (&a[0] > &b[0]) << '\n'; // Print the result of comparing the *pointers*
Run Code Online (Sandbox Code Playgroud)
随着s1>s2您调用的operator>功能std::string。该表达式s1 > s2等效于s1.operator>(s2)。