C++:如何为char数组制作比较函数?

New*_*bie 2 c++ operator-overloading

这可能吗?当我把char作为类型时,我得到奇怪的错误消息:

inline bool operator==(const char *str1, const char *str2){
    // ...
}
Run Code Online (Sandbox Code Playgroud)

错误信息:error C2803: 'operator ==' must have at least one formal parameter of class type...我根本不明白.

我在想是否可以直接比较像:

const char *str1 = "something";
const char *str2 = "something else";
const char str3[] = "lol"; // not sure if this is same as above
Run Code Online (Sandbox Code Playgroud)

然后比较:

if(str1 == str2){
   // ...
}
Run Code Online (Sandbox Code Playgroud)

等等

但我也希望它能与之合作:

char *str = new char[100];
Run Code Online (Sandbox Code Playgroud)

和:

char *str = (char *)malloc(100);
Run Code Online (Sandbox Code Playgroud)

我假设我使用这种方式的每个char数组都会以NULL字符结束,所以检查应该是可能的,但我知道它可能是不安全的等等.我只是想知道这是否可行,以及如何.

ypn*_*nos 7

这不可能.正如您的编译器指出的那样,您不能为原始数据类型重载此运算符.比较的至少一侧必须是非原始的,以使过载成为可能.

同样,您无法从原始数据类型派生新类(向其添加功能).