I am trying to define operator + for string and double using the following function
string operator + (const double& b,const string a){
return to_string(b)+a;
}
When I am doing the following operation, it works well
double c = 100.256;
string d = "if only";
cout<<c+d<<"\n";
but when i pass const char instead of string , it throws compilation error(invalid operands of types ‘double’ and ‘const char [4]’ to binary ‘operator+’)
double c = 100.256;
string test = c+"sff";
Why is implicit conversion of const char[] "sff" to string not happening?
According to the C++ 17 Standard (16.3.1.2 Operators in expressions)
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.
In this expression
c+"sff"
(where c
is a scalar value of the type double
) neither operand has a class or an enumeration type and a built-in operator + for types double
and const char *
is not defined. The pointer arithmetic is defined when a second operand has an integer type.