【发布时间】:2020-12-01 04:25:05
【问题描述】:
我正在尝试使用以下函数为字符串和双精度定义运算符 +
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" 隐式转换为字符串?
【问题讨论】:
-
好吧,因为 char * 不是字符串
-
而且你最好接受你的 double 值,字符串 const 引用
-
@pm100:存在从
const char *到std::string的隐式转换。好的答案是为什么它不能在这里使用。 -
试试
std::string operator+(const double b, std::string_view a) { return std::to_string(b) + std::string(a); } std::string test = c + "sff"s; -
@pm100 这不是一条有用的评论。
标签: c++ operator-overloading operator-keyword explicit-conversion