r/cpp_questions • u/onecable5781 • 7d ago
OPEN Operator + overloads on std::string
Consider https://godbolt.org/z/oY9r59P5E
#include <string>
const char *temp = "Hello";
std::string returnstring(){
return "abc";
}
int main(){
std::string abc = temp + returnstring() + "_";
std::string def = temp + "_";
}
The second line in main() does not compile with the error of "invalid operands". The first line compiles fine and that can only be due to the intervening "returnstring()" call which returns an std::string, somehow.
What is the cleanest way to get the intent behind the second line to compile? In my application, I cannot change const char * temp into an std::string.
7
Upvotes
View all comments
2
u/mkhanwrites_ 7d ago
I get the error " error: invalid operands of types ‘const char*’ and ‘const char [2]’ to binary ‘operator+’ ".
It seems the binary operator + is not defined for two C-style string operands. One string needs to be an std::string, because then the use of "+" will invoke the binary operator+ overload for std::string, which is defined for std::string and C-style string operands.