c++ - 在 cpp 中为 double 和 string 数据类型定义运算符 +

标签 c++ operator-overloading operator-keyword explicit-conversion

我正在尝试使用以下函数为字符串和双定义运算符 +

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/

相关文章:

c++ - QObject 派生类有哪些要求?

C++避免代码重复运算符重载

c++ - 如何调用对象/构造函数以返回二维数组

javascript - 三元运算符的奇怪行为

c# - C#中的Cast操作优先级

c# - c#中的声明是分配内存还是分配内存的新运算符?

c++ - QML QTQuick ChartView 将指针传递给 C++

c++ - 找到 g++ 使用的 STL header 的路径

c++ - 重载赋值操作/流

c++ - 数字常量之前的预期主表达式