在C++中,std :: string类实现了比较运算符.下面的代码打印AAA
#include <iostream>
using namespace std;
int main() {
if("9">"111")
cout << "AAA";
else
cout << "not AAA";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这个片段打印not AAA:
#include <iostream>
using namespace std;
int main() {
if("9">"111")
cout << "AAA";
else
cout << "not AAA";
if("99">"990")
cout << "BBB";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
为什么会这样?
您正在比较静态持续时间存储中某处的字符串文字的地址,并且它具有未指定的行为.
std::string像这样使用
#include <iostream>
using namespace std;
int main() {
if(std::string("9") > std::string("111"))
cout << "AAA";
else
cout << "not AAA";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编辑
有了using namespace std::literals;一个可以用"9" S和"111"秒.
谢谢@sp2danny