程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> 跟蹤與調試

跟蹤與調試

編輯:C++入門知識

/*
    許多C++程序員在跟蹤代碼時通常的做法是,定義一個簡單的Trace類將診斷信息打印到日志文件中。程序員
可以在每個想要跟蹤的函數中定義一個Trace對象,在函數的入口和出口Trace類可以分別寫一條信息。
    缺點:增加程序開銷,必須重新編譯程序來打開或關閉跟蹤。
     */
class Trace
{
public:
 Trace(conse string &name);
 ~Trace(); www.2cto.com
 void debug(const string &msg);

 static BOOL traceIsActive;
private:
 string theFunctionName;
};

inline Trace::Trace(const string &name) : theFunctionName(name)
{
 if (traceIsActive)
 {
  cout << "Enter function " << name <<endl;
 }
}

inline Trace::debug(const string &msg)
{
 if (traceIsActive)
 {
  cout <<  msg <<endl;
 }
}

inline Trace::~Trace()
{
 if (traceIsActive)
 {
  cout << "Exit function " << theFunctionName <<endl;
 }
}

int myFunction(int x)
{
 #ifdef TRACE
 Trace t("myFunction");   //構造函數以一個函數名作為參數。
 t.debug("Some information message");
 #endif

}

//以上的代碼存在性能問題,優化版:
class Trace
{
public:
 Trace(const char* name);
 ~Trace();
 void debug(const char* msg);

 static BOOL traceIsActive;
private:
 string* theFunctionName;
};

inline Trace::Trace(const char* name) : theFunctionName(NULL)
{
 if (traceIsActive)
 {
  cout << "Enter function " << *name <<endl;
  theFunctionName = new string(*name);
 }
}

inline Trace::debug(const char* msg)
{
 if (traceIsActive)
 {
  cout <<  *msg <<endl;
 }
}

inline Trace::~Trace()
{
 if (traceIsActive)
 {
  cout << "Exit function " << *theFunctionName <<endl;
  delete theFunctionName;
 }
}

int myFunction(int x)
{
#ifdef TRACE
 char* name = "myFunction";
 Trace t(name);   //構造函數以一個函數名作為參數。
#endif

}

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved