开发者

String operators C++

开发者 https://www.devze.com 2023-04-09 01:10 出处:网络
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

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?


In C++ operator == for std::string compares the content of the strings.


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.


There is already a bunch of operators implemented for std::string (compare std::string and const char* etc.)

If you have a custom type, then you'll need to provide operators for those.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号