Pages

Wednesday, 4 April 2018

Chapter 8 // Drill 3 - Principles & Practice Using C++

In this exercise I am using Visual Studio Community 2017 and the header file "std_lib_facilities.h" which can be found here:

http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h


Chapter 8 // Drill 3



3. Write a program using a single file containing three namespaces X, Y, and Z so that the following main() works correctly:

int main()
{
X::var = 7;
X::print(); //print X's var

using namespace Y;
var = 9;
print(); //print Y's var

{
using Z::var;
using Z::print;
var = 11;
print(); //print Z's var
}

print(); //print Y's var
X::print(); //print X's var

}

Each namespace needs to define a variable called var and a function called print() that outputs the appropriate var using cout.


#include "std_lib_facilities.h"

namespace X {
 double var;

 void print()
 {
  cout << "X: " << var << endl;
 }
}

namespace Y {
 double var;

 void print()
 {
  cout << "Y: " << var << endl;
 }
}

namespace Z {
 double var;

 void print()
 {
  cout << "Z: " << var << endl;
 }
}

int main()
{
 X::var = 7;
 X::print();  //print X's var

 using namespace Y;
 var = 9;
 print();  //print Y's var

 {
  using Z::var;
  using Z::print;
  var = 11;
  print(); //print Z's var
 }

 print();  //print Y's var
 X::print();  //print X's var

 keep_window_open();

 return 0;
}

No comments:

Post a Comment