[英]comparing string object with string literal in C++: why no compile errors?
我写了一些这样的代码:
#include<string>
using namespace std;
int main() {
string str;
...
if(str=="test") //valid????
//do something
...
return 0;
}
稍后重新阅读代码后,我很好奇编译器没有给出任何错误?
注意:我已经检查了引用,并且看起来应该存在某种类型的不匹配错误(将字符串对象与char数组进行比较)
编辑:对不起= = =拼写错误。 它已经固定
编辑2:问题:
正如其他人提到的那样,单个=
符号执行赋值,而不是比较。
但是比较运算符就像赋值一样是由运算符重载定义的, 运算符重载是C ++的最基本功能之一。
表达式str = "test"
转换为函数调用str.operator= ("test")
,表达式str == "test"
将转换为str.operator== ("test")
或operator==(str,"test")
,无论哪个可行。
即使未为std::string
和char *
操作数定义重载函数,编译器仍会尝试查找函数以将参数转换为与该函数匹配的类型。
编辑:啊, std::string
无法转换为bool
因此if
条件仍然是错误。 我认为这是为问题制作一个不错的摘录的产物。
if(str="test") //it's an assignment not a comparison.
将其更改为if(str=="test")
why no compile errors?
因为它是c ++而不是c。 std::string
定义了此==
运算符。
if(str="test") //it's an error: because you can't convert string to boolean type.
which is expected as condition.
error like :could not convert 's.std::basic_string<_CharT, _Traits, _Alloc>::operator=
<char, std::char_traits<char>, std::allocator<char> >(((const char*)"p"))' from
'std::basic_string<char>' to 'bool'
如果你这样做
if(str="test"){}
您将“ test”分配给str
。 由于这是有效操作,因此赋值将返回&str
对您的对象的引用,因此您的if条件将始终得到满足。 当然,如果str == 0
,则将给出错误。 所以最好做:
if(str == "test"){}
感谢James Kanze!
如前所述,这不是由于运算符重载而引起的编译错误(忽略您不是在进行比较而是在分配的事实)。 如果使用不带该运算符的任何对象,则是的,这将是编译错误:
// Foo does not have comparision operator
struct Foo {};
// Bar have comparision operator
struct Bar
{
// Next line is the operator overload.
bool operator ==(const char *pstr) const { return true; };
};
// string have comparision operator
std::string Test("test");
if (Foo == "test") // compilation error
if (Bar == "test") // uses the Bar::operator ==
if (Test == "test") // uses the basic_string<char>::operator ==
{ /* do something */ }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.