zoukankan      html  css  js  c++  java
  • C++ 进阶

    C++面对对象设计其中常常涉及到有关跟踪输出的功能,这是C++进阶的一个非常基础的问题;

    以下样例将实现这一功能;

    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;
    };


    上述样例中用一个noisy跟踪输出;
    另外,因为这些成员函数定义在Trace类自身的定义内,C++会内联扩展它们。所以就使得即使在不进行跟踪的情况下。在程序中保留Trace类的对象也不必付出多大的代价,。仅仅要让print函数不做不论什么事情,然后又一次编译程序,就能够有效的关闭全部对象的输出;

    还有一种改进:

    在面对对象时,用户总是要求改动程序;比方说。涉及文件输入输出流。将要输出的文件打印到标准输出设备以外的东西上;


    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;
    };

    Trace类中有两个构造函数。第一个是无參数的构造函数,其对象的成员f为stdout,因此输出到stdout。还有一个构造函数同意明白指定输出文件!

    完整程序:

    #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() ");
    t.print("end main() ");
    }

  • 相关阅读:
    Autofac(01)
    深入理解ADO.NET Entity Framework(02)
    使用excel 数据透视表画图
    C# 控制CH341进行SPI,I2C读写
    C# winform使用combobox遍历文件夹内所有文件
    通用分页存储过程
    如何让你的SQL运行得更快
    sql优化之使用索引
    SQL优化
    SQL 循环语句几种写法
  • 原文地址:https://www.cnblogs.com/jhcelue/p/6785314.html
Copyright © 2011-2022 走看看