Ok, I'm learning C++ through a book I found online (Fundamentals of C+ Programming by Richard L. Halterman). After each chapter there is some exercises.
The exercise I need help with is as following:
3. The following C++ program is split up over three source files. The first file, counter.h, consists of
1 2 3 4 5
|
// counter.h
int read();
int increment();
int decrement();
|
The second file, counter.cpp, contains
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
// counter.cpp
static int count;
int read() {
return count;
}
int increment() {
if (count < 5)
count++;
}
int decrement() {
if (count > 0)
count--;
}
|
The third file, main.cpp, is incomplete:
1 2 3 4 5 6 7 8 9
|
// main.cpp
#include <iostream>
#include "counter.h"
using namespace std;
int main() {
// Add code here
}
|
(a) Add statements to main that enable it to produce the following output:
The restriction is that the only output statement you are allowed to use (three times) is
(b) Under the restriction of using the same output statement above, what code could you add to main so that it would produce the following output?
Ok, so (a) is pretty easy. But I need a little help with (b)...
The chapter with this exercise was about global variables, static variables, header files, and pointers at last. So I guess I need to use pointers in some way..
I've tried a couple of different things, but non of them worked..
Here's my code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
// My main.cpp file
#include <iostream>
#include "counter.h"
using namespace std;
int main()
{
// Print out 3
increment();
increment();
increment();
cout << read() << endl;
// Print out 2
decrement();
cout << read() << endl;
// Print out 4
increment();
increment();
cout << read() << endl;
// Print out 6
// What to do here??
}
|
Of course it prints out:
So.. Please help :)
And thank you in advance!