我正在尝试使用以下函数为字符串和双定义运算符 +
string operator + (const double& b,const string a){
return to_string(b)+a;
}
当我进行以下操作时,效果很好double c = 100.256;
string d = "if only";
cout<<c+d<<"\n";
但是当我传递 const char 而不是 string 时,它会抛出编译错误('double'和'const char [4]'类型的无效操作数到二进制'operator+')double c = 100.256;
string test = c+"sff";
为什么没有发生 const char[] "sff"到字符串的隐式转换?
最佳答案
根据 C++ 17 标准(表达式中的 16.3.1.2 运算符)
1 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 8.
在这个表达式中
c+"sff"
(其中 c
是类型 double
的标量值)两个操作数都没有类或枚举类型以及类型 double
的内置运算符 +和 const char *
没有定义。当第二个操作数具有整数类型时定义指针算术。
关于c++ - 在 cpp 中为 double 和 string 数据类型定义运算符 +,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63359274/