Source of namespace3.cpp


  1: //namespace3.cpp
  2: //Illustrates a not-all-in-one-place namespace and functions in namespaces.

  4: #include <iostream>
  5: #include <iomanip>
  6: using namespace std;

  8: #include "utilities.h"
  9: using Scobey::Pause;

 11: namespace MyStuff
 12: {
 13:     //Here are two versions of MyStuff::DoIt.
 14:     //Note that in this case the the full definition of each is given.
 15:     void DoIt() //version 1
 16:     {
 17:         cout << "\nDoing it my way ...\n";
 18:     }

 20:     void DoIt //version 2
 21:     (
 22:         int indentLevel //in
 23:     )
 24:     {
 25:         cout << "\n" << setw(indentLevel) << ""
 26:             << "Doing it my way and indented ...\n";
 27:     }
 28: }

 30: namespace YourStuff
 31: {
 32:     void DoIt(); //This of course is YourStuff::DoIt.
 33:     //This is just a prototype; the definition appears below.
 34: }

 36: void DoIt() //This is a global DoIt.
 37: {
 38:     cout << "\nDoing it any ol' way ...\n";
 39: }

 41: int main()
 42: {
 43:     //using namespace MyStuff;     //1
 44:     //using namespace YourStuff;   //2
 45:     //using MyStuff::DoIt;         //3
 46:     //using YourStuff::DoIt;       //4

 48:     DoIt();
 49:     Pause(0, "", 1);

 51:     MyStuff::DoIt(6);
 52:     Pause(0, "", 2);
 53: }

 55: void YourStuff::DoIt() //Definition corresponding to above prototype
 56: {
 57:     cout << "\nDoing it your way ...\n";
 58: }

 60: /*
 61: Questions:
 62: 1. What is output if the program is run as is?
 63: 2. What is output if comment //1 is activated?
 64: 3. What is output if comment //2 is activated?
 65: 4. What is output if comment //3 is activated?
 66: 5. What is output if comment //4 is activated?

 68: Answers:
 69: 1. Doing it any ol' way ...
 70:          Doing it my way and indented ...
 71: 2. namespace3.cpp(48) : error C2668: 'DoIt' : ambiguous
 72:    call to overloaded function
 73: 3. namespace3.cpp(48) : error C2668: 'DoIt' : ambiguous
 74:    call to overloaded function
 75: 4. Doing my way ...
 76:          Doing it my way and indented ...
 77: 5. Doing your way ...
 78:          Doing it my way and indented ...
 79: */