C + + Face object design often involves the function of trace output, which is a very basic problem of C + + advanced;
The following example will implement this function;
Class Trace {
Public
Trace () {noisy = 0;}
void print (char *s) {if (noisy) printf ("%s", s);}
void on () {noisy = 1;}
void off () {noisy = 0;}
Private
int noisy;
};
The above example uses a noisy to trace the output;
Also, because these member functions are defined within the definition of the trace class itself, C + + expands them inline. So it makes even the case without tracking. It does not cost much to keep the object of the Trace class in the program. Just let the print function do no matter what, and then compile the program again, you can effectively close the output of all objects;
There is also an improvement:
In the face of the object, users always ask to change the program; involves the file input and output stream. Print the file you want to output to something other than the standard output device;
Class Trace {
Public
Trace () {noisy = 0; f = stdout;}
Trace (FILE *ff) {noisy = 0; f = ff;}
void print (char *s) {if (noisy) fprintf (F, "%s", s);}
void on () {noisy = 1;}
void off () {noisy = 0;}
Private
int noisy;
FILE *f;
};
There are two constructors in the Trace class. The first is a non-parameter constructor whose object's member F is stdout, so it is output to stdout. There is also a constructor that agrees to understand the specified output file!
Complete program:
#include <stdio.h>
Class Trace {
Public
Trace () {noisy = 0; f = stdout;}
Trace (FILE *ff) {noisy = 0; f = ff;}
void print (char *s) {if (noisy) fprintf (F, "%s", s);}
void on () {noisy = 1;}
void off () {noisy = 0;}
Private
int noisy;
FILE *f;
};
int main ()
{
Trace T (stderr);
T.print ("Begin main () \ n");
T.print ("end main () \ n");
}
C + + Advanced