1.CDumpContext
该类没有基类。这个类支持面向流的诊断输出,以人能够阅读的文本。该类重载了<<操作符。
afxDump是一个预声明的CDumpContext对象,可以方便使用。该对象只在MFC的Debug版中有效。可以将调式信息输出到调试输出窗口或调试终端。
// example for afxDumpCPerson myPerson = new CPerson;// set some fields of the CPerson object...//..// now dump the contents#ifdef _DEBUGafxDump << "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 TRACE0TRACE0( "Start Dump of MyClass members:" );
// example for TRACE1int i = 1;TRACE1( "Integer = %d/n", i );// Output: 'Integer = 1'
// example for TRACE2int 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 _DEBUGvoid 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 _DEBUGCFile 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
在较复杂的程序中,我们可以采用上述方法,
在调试程序的过程中,输出自己想要的数据和信息。
还是较为方便和简单的方法的。