How to interpret “operator const char*()” in opera

2019-04-01 00:30发布

问题:

I was looking at one of the implementation of String class and noticed the following overloaded == operator.

String f = "something";
String g = "somethingelse";
if (f == g)
    cout << "Strings are equal." << endl;

bool operator==(String sString)
{
    return strcmp(operator const char*(), (const char*)sString) == 0; 
}

I understood most of the part except operator const char*() what exactly its been used for? I have very basic knowledge of operator overloading , can someone please throw some more light on this?

回答1:

It is an explicit call to the operator const char*() member function. This code would do the same:

return strcmp(static_cast<const char*>(*this), (const char*)sString) == 0;

But there are more than one thing wrong with that code:

  1. it should not use C-cast, but C++-casts (e.g. static_cast) for the right argument
  2. operator== should be a free function, not a member function
  3. A string class should normally not have an operator const char*
  4. If the String class is implemented reasonably, the operator== should take both parameters as const references


回答2:

operator const char*() is the old-style C casting: just like you can cast an integer to float by (float)int_var, you can cast to const char* as (const char*)string_var. Here it cast a String to const char *

If you're familiar with the STL std::string, then this operator const char*() is doing basically the same job as .c_str() there.



回答3:

This is an explicit call to the cast-to-const char* operator which is overloaded by your String implementation.



回答4:

This operator will cast it's own String to const char* and call strcmp.