[英]Shouldn't char* implicitly converted to std::string?
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? 我想知道为什么从char *到string的隐式转换在这里不起作用?
UPDATE Anton's answer makes sense, I updated the code: 更新Anton的答案是有道理的,我更新了代码:
#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: §13.3.1.2表达式[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. 如果表达式中的运算符的操作数没有类或枚举类型,则假定运算符是内置运算符并根据条款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. 这正是你的情况: operator==
的参数是指针,所以它被认为是内置的,编译器不会寻找可能的重载。
Absolutely not. 绝对不。
First of all, you are trying to use a pointer in place of a reference. 首先,您尝试使用指针代替引用。 Any similarity between a pointer and a reference is a implementation detail. 指针和引用之间的任何相似性都是实现细节。 Remember the motto: "Implementation Is Irrelevant!" 记住座右铭:“实施是不相关的!”
Next, and more directly to your question, a std::string and a char* are quite different, even if they are used to represent the same things. 接下来,更直接地讨论你的问题,std :: string和char *是完全不同的,即使它们用于表示相同的东西。 Conversion between them was deliberately made difficult to prevent using them interchangably. 故意使它们之间的转换难以防止可互换地使用它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.