天天看點

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

TRACE1( "Integer = %d/n", i );

// Output: 'Integer = 1'

// example for TRACE2

TRACE2( "Integer = %d, String = %s/n", i, sz );

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:

//聲明

    virtual void Dump( CDumpContext& dc ) const;

    CString m_firstName;

    CString m_lastName;

    // etc. ...

};

//實作

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

//調用

CPerson person;

if( !f.Open( "c://dump.txt", CFile::modeCreate | CFile::modeWrite ) ) {

person.Dump(dc);

dc<<"test dump output";

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

在調試程式的過程中,輸出自己想要的資料和資訊。

還是較為友善和簡單的方法的。

繼續閱讀