这是我的代码:
#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;
}
编译错误:
prog.cpp:14:12: error: comparison between distinct pointer types ‘ST*’ and ‘const char*’ lacks a cast [-fpermissive]
if (st == p) {
^
我想知道为什么从 char* 到 string 的隐式转换在这里不起作用?
更新 安东的回答有道理,我更新了代码:
#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;
}
现在可以编译了。
最佳答案
§13.3.1.2 Operators in expressions [over.match.oper]状态:
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.
这正是您的情况:operator==
的参数是指针,因此它被认为是内置的,编译器不会寻找可能的重载。
关于c++ - char* 不应该隐式转换为 std::string 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25648460/