Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何在C++;_C++_String_Comparison_Const String - Fatal编程技术网

C++ 如何在C++;

C++ 如何在C++;,c++,string,comparison,const-string,C++,String,Comparison,Const String,假设我有以下poc代码: const string& a = "hello"; string b = "l"; if(a.at(2) == b) { // do stuff } 我知道没有与这些操作数匹配的运算符“==”。而且,修复它的方法是将变量a的值转换为“hello”(而不是双引号)作为char 但是,如果我别无选择,只能执行代码中所示的比较,该怎么办。可能吗?你能提供一些关于这个问题的指导或建议吗 感谢您的回复 const string& a = "hello";

假设我有以下poc代码:

const string& a = "hello";
string b = "l";

if(a.at(2) == b)
{
 // do stuff
} 
我知道没有与这些操作数匹配的运算符“==”。而且,修复它的方法是将变量a的值转换为“hello”(而不是双引号)作为char

但是,如果我别无选择,只能执行代码中所示的比较,该怎么办。可能吗?你能提供一些关于这个问题的指导或建议吗

感谢您的回复

const string& a = "hello";
string b = "l";

if (a[2] == b[0])
{
    // do stuff
}
a、 at(2)不是字符串。什么时候做b到b[0]的问题解决


a、 at(2)不是字符串。当进行b到b[0]问题解决时。

您正在比较一个
字符
(具体地说是
常量字符
)和一个
标准::字符串
,其中()没有重载的比较运算符

您有一些选择:

(1) 将
b
的第一个字符与要比较的字符进行比较

string b = "l";
string a = "hello";
if(a[2] == b[0]) { /* .. */ }
(2) 将
a[2]
转换为
std::string

string b = "l";
string a = "hello";
if(string{a[2]} == b) { /* .. */ }
(3) 让
b
成为
char

char b = 'l';
string a = "hello";
if(a[2] == b) { /* .. */ }
此外,您不应该像这样构造字符串对象

const string& a = "hello";
除非您确实想要创建对另一个字符串对象的引用,例如

string x = "hello";
const string& a = x;

您正在比较
char
(具体地说是
const char
)和
std::string
,其中()不存在重载的比较运算符

您有一些选择:

(1) 将
b
的第一个字符与要比较的字符进行比较

string b = "l";
string a = "hello";
if(a[2] == b[0]) { /* .. */ }
(2) 将
a[2]
转换为
std::string

string b = "l";
string a = "hello";
if(string{a[2]} == b) { /* .. */ }
(3) 让
b
成为
char

char b = 'l';
string a = "hello";
if(a[2] == b) { /* .. */ }
此外,您不应该像这样构造字符串对象

const string& a = "hello";
除非您确实想要创建对另一个字符串对象的引用,例如

string x = "hello";
const string& a = x;

const string a=“你好”字符b='l'显示此代码生成的消息。
const string a=“hello”字符b='l'显示此代码生成的消息。我一定一直在产生幻觉。谢谢你的启发。我一定一直在产生幻觉。谢谢你的启发。谢谢你对这些选项的详细分类。在我的代码中,我实际上将“conststring&a”作为函数参数传递。感谢您对这些选项的详细分析。在我的代码中,我实际上将“conststring&a”作为函数参数传递。