锐凌加油机官网:ASSERT_VALID

来源:百度文库 编辑:九乡新闻网 时间:2024/04/24 22:57:10
ASSERT_VALID宏的利用 2010-10-22 08:48ASSERT_VALID宏用来在运行时检查一个对象的内部合法性,比如说现在有一个学生对象,我们知道每个学生的年龄一定大于零,若年龄小于零,则该学生对象肯定有问题。


事实上,ASSERT_VALID宏就是转化为对象的成员函数AssertValid()的调用,只是这种方法更安全。它的参数是一个对象指针,通过这个指针来调用它的AssertValid()成员函数。

与此相配套,每当我们创建从Cobject类继承而来的一个新的类时,我们可以重载该成员函数,以执行特定的合法性检查

 

ASSERT_VALID

ASSERT_VALID( pObject )

Parameters

pObject

Specifies an object of a class derived from CObject that has an overriding version of the AssertValid member function.

Remarks

Use to test your assumptions about the validity of an object’s internal state. ASSERT_VALID calls the AssertValid member function of the object passed as its argument.

In the Release version of MFC, ASSERT_VALID does nothing. In the Debug version, it validates the pointer, checks against NULL, and calls the object’s own AssertValid member functions. If any of these tests fails, this displays an alert message in the same manner as ASSERT.

Note    This function is available only in the Debug version of MFC.

For more information and examples, see MFC Debugging Support in Visual C++ Programmer’s Guide.

-----------------------------------------
以下是我个人翻译,如有错误,请指正,不胜感激

说明:

用来测试你关于对象内部状态合法性的假定。ASSERT_VALID调用作为参数的被调用对象的AssertValid成员函数。

在MFC RELEASE版本下,ASSERT_VALID什么都不做。在DEBUG模式下,该函数验证指针是否为NULL,并且调用AssertValid成员函数。如果任何测试出错,将像ASSERT一样显示一个警告信息。

提示:该函数仅在MFC DEBUG模式下起作用。

更多信息和例子,参见MFC Debugging Support in Visual C++ Programmer’s Guide.

例子:

在Win32环境下通过测试

#include

class CPerson : public CObject
{
public:

       CPerson(char *pName, int nAge);

#ifdef _DEBUG

       virtual void AssertValid() const;

#endif

private:

       char *m_strname;

       int m_nage;
};

CPerson::CPerson(char *pName, int nAge) : m_strname(pName), m_nage(nAge)
{

}

#ifdef _DEBUG

void CPerson::AssertValid() const
{

       CObject::AssertValid();

       ASSERT(m_strname);

       ASSERT(m_nage>0);
}

#endif

int main()
{

       CString strName("listen");

       CPerson *pPersonOne = new CPerson(strName.GetBuffer(0), -5);

#ifdef _DEBUG

       pPersonOne->AssertValid();

#endif

       return 0;
}