这可能吗?当我将 char 作为类型时,我收到奇怪的错误消息:
inline bool operator==(const char *str1, const char *str2){
// ...
}
错误信息:error C2803: 'operator ==' must have at least an 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
然后比较:
if(str1 == str2){
// ...
}
等等
但我也希望它能与:
char *str = new char[100];
和:
char *str = (char *)malloc(100);
我假设我以这种方式使用的每个字符数组都将以 NULL 字符结尾,因此应该可以进行检查,但我知道它可能不安全等等。我只想知道这是否可行,以及如何执行。
最佳答案
这是不可能的。正如您的编译器指出的那样,您不能为原始数据类型重载此运算符。至少比较的一侧必须是非原始的,才能进行重载。
同样,您不能从原始数据类型派生新类(向其添加功能)。
关于C++:如何为字符数组创建比较函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4670754/