字符串运算符 C++
我想知道是否可以使用 ==
比较两个字符串。我有一个接受 const value &item
的函数,并且由于它是 value
类型,因此我无法确定该值是什么类型,因此如果 < code>value 类型是 string
,==
可能不起作用。
因此问题是,解决这个问题的最佳方法是什么?我正在考虑重载 ==
运算符,但是有一个简单的方法吗?
I was wondering if you can compare two strings using ==
. I have a function which takes in a const value &item
and since its a value
type there is no way I can determine what type the value is, hence if the value
type is a string
, ==
may not work.
Hence the question, what would be the best way to tackle this problem? I was thinking of overloading the ==
operator, but is there an easy way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 C++ 中,
std::string
的运算符 == 比较字符串的内容。In C++
operator ==
forstd::string
compares the content of the strings.如果字符串是
std::string
它已经定义了一个operator==。它比较字符串的内容。如果它是 C 字符串 (
char*
),则比较是指针比较,它告诉我们指针是否指向同一字符串。您也不能重载它,因为它是内置运算符。If the string is a
std::string
it already has an operator== defined. It compares the contents of the strings.If it is a C string (
char*
) the comparison is a pointer comparison that tells us if the pointers points to the same string. You cannot overload this either as it is a built in operator.已经有一堆为
std::string
实现的运算符(比较std::string
和const char*
等)如果你有自定义类型,那么您需要为它们提供运算符。
There is already a bunch of operators implemented for
std::string
(comparestd::string
andconst char*
etc.)If you have a custom type, then you'll need to provide operators for those.