C + + Advanced

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.