Accelerated C++ Chapter01

どうもです。
Accelerated C++ をやっとこさ終えました。
ほいで,復習のために,Chapter1から順に,簡単なメモと,Exercises のオレオレ解答を
アップしていこうという企画。


ついでに,1度やったExercisesのコードを綺麗にしていったりね。
後ろの方の章で書いたテストに,すごい繰り返しやら重複やらがあるから,
リファクタリングの勉強にもいいだろうし。

感想

Chapter1では,Cに比べて,簡単に入出力ができまっせということを
見せつけられた感たっぷり。
しかしこの時には,後にprintf(3)が恋しくなることをまだ知らないのであった・・・。

解答

#include <iostream>
#include <string>

using namespace std;

void ex1_1()
{
  const std::string hello = "Hello";
  const std::string message = hello + ", world" + "!";
}

void ex1_2()
{
  const std::string exclam = "!";
  // The following is NOT valid because there is no +operator which
  // concatenates two const char*s
  //const std::string message = "Hello" + ", world" + exclam;
}

void ex1_3()
{
  cout << "==================== ex1_3 ====================" << endl;
  {
    // a scope
    const std::string s = "a string";
    cout << s << endl;
  }

  {
    // another scope
    const std::string s = "another string";
    cout << s << endl;
  }

  cout << "ex1_3 is valid" << endl;
}

void ex1_4()
{
  cout << "==================== ex1_4 ====================" << endl;
  {
    const std::string s = "a string";
    cout << s << endl;
    {
      // The following s shadows the outer s, so these are also valid.
      const std::string s = "another string";
      cout << s << endl;
    }; // Even if `;' is added, it's valid.
  }; // Also, it's ok if we add it here.
}

void ex1_5()
{
  cout << "==================== ex1_5 ====================" << endl;
  {
    std::string s = "a string";
    {
      std::string x = s + ", really";
      // Output s defined in the outer scope
      cout << s << endl;
      cout << x << endl;
    }
  }
}

void ex1_6()
{
  cout << "==================== ex1_6 ====================" << endl;
  cout << "What is your name?: ";
  string name;
  cin >> name;
  cout << "Hello, " << name << endl;
  cout << "And what is yours?: ";
  cin >> name;
  cout << "Hello, " << name << "; nice to meet you too!" << endl;
}

int main()
{
  ex1_1();
  ex1_2();
  ex1_3();
  ex1_4();
  ex1_5();
  ex1_6();

  return 0;
}