I have read numerous posts as to why two string literals cannot be added in C++, etc, and the operator+ support adding a string literal to an integer.
However, I am trying to understand the compiler error in the following code:
string str1, str2, str3;
int i = 10;
str1 = "Hello " + i;
str2 = i + "Mars";
str3 = "Hello " + i + "Mars";
Initialization of str1
and str2
works fine, but the construction of str3
gives the following error:
example.cpp: In function
int main()
:
example.cpp:20:27: error: invalid operands of typesconst char*
andconst char [5]
to binaryoperator+
Q1: In the error message, I understand const char [5]
refers to "Mars"
. What does const char*
refer to, the integer i
after conversion to a char *
?
Q2: operator+
has left-to-right associativity, I am guessing the construction of str3
can be written as:
str3 = ("Hello " + i) + "Mars";
Does ("Hello " + i)
evaluate to a char *
?
Q3: In the following code:
str5 = string("foo ") + "bar ";
str6 = string("foo ") + "bar " + i;
Setting of str5
compiles fine, but str6
generates loads (page and half) of error messages. What is the outcome of string("foo ") + "bar "
, is it a "string"
?
Thanks in advance for any insight.