3

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?

5
  • 7
    Well because a char * is not a string Commented Aug 11, 2020 at 13:35
  • 8
    And you better accept your double by value, and string by a const reference Commented Aug 11, 2020 at 13:35
  • 5
    @pm100: there is an implicit convertion from const char * to std::string. The good answer would be why it cannot be used here. Commented Aug 11, 2020 at 13:38
  • 1
    Try std::string operator+(const double b, std::string_view a) { return std::to_string(b) + std::string(a); } std::string test = c + "sff"s; Commented Aug 11, 2020 at 13:42
  • @pm100 That wasn't a useful comment. Commented Aug 11, 2020 at 13:46

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Can using a struct also (In addition to class, enum) allow an addition. IOW, is my answer correct? Someone DVoted but didn't tell the reason.
@anki, a class in the C++ standard usually refers to both struct and class

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.