Solutions to Chapter 1

1-0. Compile, execute and test the programs in this chapter.

Answer: not applicable.

1-1. Are the following definitions valid? Why and why not?

const std::string hello = “Hello”;

const std::string message = hello + “, world” + “!”;

Answer:  Yes.

1-2. Are the following definitions valid? Why and why not?

const std::string exclam = “!”;

const std::string message1 = “Hello” + “, world” + exclam;

Answer: Unfortunately, the second statement will cause an “invalid operands to binary expressions(‘const char*’ and ‘const char*’). Which happend at ‘”Hello” + “, world”‘.

There is no ‘+’ operator to add two C-style strings – char *, char[]. while the “Hello” and “, world” alike strings are actually C-style strings. But the string from standard library contains the ‘+’ operator which should do the right job. So simply change the code to the following and it will work:

const std::string exclam = “!”;

const std::string message1 = std::string(“Hello”) + std::string(“, world”) + exclam;

 

to be continued…

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s