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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With