现在的位置: 首页 > 综合 > 正文

MFC中对象的初始化

2013年01月27日 ⁄ 综合 ⁄ 共 1335字 ⁄ 字号 评论关闭
在MSDN中看到,关于MFC对象初始化的说明。

One-Stage
and Two-Stage Construction of Objects

You have a choice between two techniques for creating grahpic objects, such as pens and brushes:

  • One-stage construction: Construct and initialize the object in one
    stage, all with the constructor.

  • Two-stage construction: Construct and initialize the object in two
    separate stages. The constructor creates the object and an initialization
    function initializes it.

Two-stage construction is always safer. In one-stage construction, the
constructor could throw an exception if you provide incorrect arguments or
memory allocation fails. That problem is avoided by two-stage construction,
although you do have to check for failure. In either case, destroying the object
is the same process.

Note   These techniques apply to creating any
objects, not just graphic objects.


Example of Both Construction Techniques

The following brief example shows both methods of constructing a pen
object:

void CMyView::OnDraw( CDC* pDC )
{
// One-stage
    CPen myPen1( PS_DOT, 5, RGB(0,0,0) );

// Two-stage: first construct the pen
    CPen myPen2;
    // Then initialize it
    if( myPen2.CreatePen( PS_DOT, 5, RGB(0,0,0) ) )   
        // Use the pen
}
上面说的是图像对象中的初始化问题,对于其他对象,也是可以用这两种方法。

抱歉!评论已关闭.