c++ - char* 不应该隐式转换为 std::string 吗?

标签 c++

这是我的代码:

#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/

相关文章:

c++ - 在 VS2005 中为我的 C++ 应用程序设置管理员权限

c++ - 将 char 转换为 int '23' > 23

c++ - 如何将 glm::vec4<float> 转换为 GLfloat*?

c++ - 流畅的接口(interface)模式和 std::unique_ptr

c++ - 将非模板基类向下转换为模板化派生类 : is it possible?

c++ - 重叠缓冲区的 memcpy

c++ - 将字符串的一部分与 STDLB 中的另一个字符串进行比较

c++ - 在某些 C++ 编译器上使用 restrict 限定符的编译器错误

c++ - 创建DLL时无法解析的外部符号

c++ - 具有抽象成员的对象(无指针)