C++编程思想 第2卷 第2章 防御性编程 调试技术 跟踪文件

用using声明,可以去掉cout前面的名字空间前缀,代码中不能使用
std::cout

代码创建一个跟踪文件,并把所有本来应该送到cout的输出送到了这个
跟踪文件。 现在必须做的所有事情就是#define TRACEON并且包含相关
的头文件

//: C03:Trace.h
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
// Creating a trace file.
#ifndef TRACE_H
#define TRACE_H
#include <fstream>

#ifdef TRACEON
std::ofstream TRACEFILE__("TRACE.OUT");
#define cout TRACEFILE__
#endif

#endif // TRACE_H ///:~

代码对头文件的简单测试

//: C03:Tracetst.cpp {-bor}
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
#include <iostream>
#include <fstream>
#include "../require.h"
using namespace std;

#define TRACEON
#include "Trace.h"

int main() {
  ifstream f("Tracetst.cpp");
  assure(f, "Tracetst.cpp");
  cout << f.rdbuf(); // Dumps file contents to file
  getchar();
} ///:~

因为cout已经被Trace.h中的宏修改成了其他东西,所以程序中所有
的cout语句现在都把信息送到了跟踪文件

输出
//: C03:Tracetst.cpp {-bor}
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
#include <iostream>
#include <fstream>
#include "../require.h"
using namespace std;

#define TRACEON
#include "Trace.h"

int main() {
  ifstream f("Tracetst.cpp");
  assure(f, "Tracetst.cpp");
  cout << f.rdbuf(); // Dumps file contents to file
  getchar();
} ///:~
 

猜你喜欢

转载自blog.csdn.net/eyetired/article/details/81604907