简体   繁体   中英

Shouldn't char* implicitly converted to std::string?

Here is my code:

#include <iostream>
using namespace std;

struct ST {};

bool operator==(const struct ST *s1, const string &s2) {
    return true;
}

int main() {
    struct ST *st = new ST();
    const char *p = "abc";

    if (st == p) {
        return 0;
    }

    return 1;
}

I get compile error:

prog.cpp:14:12: error: comparison between distinct pointer types ‘ST*’ and ‘const char*’ lacks a cast [-fpermissive]
  if (st == p) {
            ^

I wonder why the implicit conversion from char* to string does not work here?

UPDATE Anton's answer makes sense, I updated the code:

#include <string>
using namespace std;

struct ST {};

bool operator==(const struct ST s1, const string &s2) {
    return true;
}

int main() {
    struct ST st;
    const char *p = "abc";

    if (st == p) {
        return 0;
    }

    return 1;
}

Now it compiles.

§13.3.1.2 Operators in expressions [over.match.oper] states:

If no operand of an operator in an expression has a type that is a class or an enumeration, the operator is assumed to be a built-in operator and interpreted according to Clause 5.

This is exactly your case: operator== 's arguments are pointers, so it's considered to be built-in and compiler doesn't look for possible overloads.

Absolutely not.

First of all, you are trying to use a pointer in place of a reference. Any similarity between a pointer and a reference is a implementation detail. Remember the motto: "Implementation Is Irrelevant!"

Next, and more directly to your question, a std::string and a char* are quite different, even if they are used to represent the same things. Conversion between them was deliberately made difficult to prevent using them interchangably.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM