C
C++ Newbie
Hi,
Consider the following program from "Accelerated C++", Koenig & Moo
[2004]:
Case [1]:
=====================================
#include <iostream>
#include <string>
int main()
{
// Ex 1-2
const std::string exclam = "!";
const std::string message2 = "Hello" + ", world" + exclam ;
std::cout << message2;
std::cout << std::endl;
return 0;
}
=====================================
The above fails to compile with the error:
1-3.cpp: In function 'int main()':
1-3.cpp:18: error: invalid operands of types 'const char [6]' and
'const char [8]' to binary 'operator+'
(Line numbers are a bit off as I snipped out irrelevant code)
If we move around the string addition a bit to a less sensible
arrangement:
Case 2:
=======================================
#include <iostream>
#include <string>
int main()
{
// Ex 1-1
const std::string hello = "Hello";
std::cout << hello;
std::cout << std::endl;
const std:: string message = hello + ", world" + "!";
std::cout << message;
std::cout << std::endl;
// Ex 1-2
const std::string exclam = "!";
const std::string message2 = "Hello" + exclam + ", world" ;
std::cout << message2;
std::cout << std::endl;
return 0;
}
====================================
The above compiles and runs.
Why does changing the arrangement of message2 make such a big
difference?
Thanks for any input.
Consider the following program from "Accelerated C++", Koenig & Moo
[2004]:
Case [1]:
=====================================
#include <iostream>
#include <string>
int main()
{
// Ex 1-2
const std::string exclam = "!";
const std::string message2 = "Hello" + ", world" + exclam ;
std::cout << message2;
std::cout << std::endl;
return 0;
}
=====================================
The above fails to compile with the error:
1-3.cpp: In function 'int main()':
1-3.cpp:18: error: invalid operands of types 'const char [6]' and
'const char [8]' to binary 'operator+'
(Line numbers are a bit off as I snipped out irrelevant code)
If we move around the string addition a bit to a less sensible
arrangement:
Case 2:
=======================================
#include <iostream>
#include <string>
int main()
{
// Ex 1-1
const std::string hello = "Hello";
std::cout << hello;
std::cout << std::endl;
const std:: string message = hello + ", world" + "!";
std::cout << message;
std::cout << std::endl;
// Ex 1-2
const std::string exclam = "!";
const std::string message2 = "Hello" + exclam + ", world" ;
std::cout << message2;
std::cout << std::endl;
return 0;
}
====================================
The above compiles and runs.
Why does changing the arrangement of message2 make such a big
difference?
Thanks for any input.