vc 調試信息輸出

 

1.CDumpContext


該類沒有基類。
這個類支持面向流的診斷輸出,以人能夠閱讀的文本。
該類重載了<<操作符。

afxDump是一個預聲明的CDumpContext對象,可以方便使用。
該對象只在MFC的Debug版中有效。
可以將調式信息輸出到調試輸出窗口或調試終端。


// example for afxDump
CPerson myPerson = new CPerson;
// set some fields of the CPerson object...
//..
// now dump the contents
#ifdef _DEBUG
afxDump << "Dumping myPerson:/n";
myPerson->Dump( afxDump );
afxDump << "/n";
#endif

如果想建立一個制定的輸出,比如一個制定的errlog文件。
我們可以自己生成一個CDumpContext對象。
方法如下:

CFile f;
if( !f.Open( "dump.txt", CFile::modeCreate | CFile::modeWrite ) ) {
   afxDump << "Unable to open file" << "/n";
   exit( 1 );
}
CDumpContext dc( &f );


2.TRACE


這個宏可以在DEBUG過程中,方便的跟蹤程序中的變量的值。
在Debug環境中,TRACE宏輸出到afxDump對象中。
在Release環境中,它不起作用。
TRACE一次限制512個字符,包括結束的NULL字符。
如果超過將引發ASSERT。


例:
int i = 1;
char sz[] = "one";
TRACE( "Integer = %d, String = %s/n", i, sz );
// Output: 'Integer = 1, String = one'

同時,還有TRACE0,TRACE1,TRACE2,TRACE3等宏。
數字代表宏中的參數數。

// example for TRACE0
TRACE0( "Start Dump of MyClass members:" );

// example for TRACE1
int i = 1;
TRACE1( "Integer = %d/n", i );
// Output: 'Integer = 1'

// example for TRACE2
int i = 1;
char sz[] = "one";
TRACE2( "Integer = %d, String = %s/n", i, sz );
// Output: 'Integer = 1, String = one'

3.void AfxDump( const CObject* pOb )
該函數調用對象的Dump成員函數,將信息輸出到afxDump制定的位置。
最好不要在程序中調用該函數,而使用對象的Dump函數。

4.virtual void Dump( CDumpContext& dc ) const;
是CObjec的成員函數,將對象的內容輸出到一個CDumpContext對象。
寫自定義類的時候,應該重寫Dump函數,來提供診斷服務。
重寫的Dump函數中一般會先調用基類的Dump函數,後輸出數據成員。
CObject::Dump輸出類名,如果你的類用了IMPLEMENT_DYNAMIC或IMPLEMENT_SERIAL宏。
例:

class CPerson : public CObject
{
public:
//聲明
#ifdef _DEBUG
    virtual void Dump( CDumpContext& dc ) const;
#endif

    CString m_firstName;
    CString m_lastName;
    // etc. ...
};
//實現
#ifdef _DEBUG
void CPerson::Dump( CDumpContext& dc ) const
{
    // call base class function first
    CObject::Dump( dc );

    // now do the stuff for our specific class
    dc << "last name: " << m_lastName << "/n"
        << "first name: " << m_firstName << "/n";
}
#endif

//調用
CPerson person;
#ifdef _DEBUG
CFile f;
if( !f.Open( "c://dump.txt", CFile::modeCreate | CFile::modeWrite ) ) {
   afxDump << "Unable to open file" << "/n";
   exit( 1 );
}
CDumpContext dc( &f );

person.Dump(dc);
dc<<"test dump output";
#endif

在較複雜的程序中,我們可以採用上述方法,

在調試程序的過程中,輸出自己想要的數據和信息。

還是較爲方便和簡單的方法的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章