Friday, February 2, 2007

explicit关键字

不常见的一个关键字,今天看到感觉有些陌生,因此写下来增进印象。:)

以下文字摘自于msdn:

This keyword is a declaration specifier that can only be applied to in-class constructor declarations.
An explicit constructor cannot take part in implicit conversions.
It can only be used to explicitly construct an object.

Note:
explicit on a constructor with multiple arguments has no effect, since such constructors cannot take part in implicit conversions.
However, for the purpose of implicit conversion, explicit will have an effect if a constructor has multiple arguments and all but one of the arguments has a default value.

关于 (This+1)

#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>

inline void * operator new(size_t iSize, void *pMem) { return pMem; }

class ThisPlusOne
{
public:
        ThisPlusOne();
        ~ThisPlusOne();
        static ThisPlusOne* Create();
public:
        const static int ArraySize;
        int* ArrayVariable;
        int MemberVariable;
};

const int ThisPlusOne::ArraySize = 20;

ThisPlusOne::ThisPlusOne():MemberVariable(0){}

ThisPlusOne::~ThisPlusOne(){}

ThisPlusOne* ThisPlusOne::Create()
{
        int iSize= sizeof(ThisPlusOne) + ArraySize*sizeof(int);
        ThisPlusOne* pThis = (ThisPlusOne*)malloc(iSize);
        pThis = new(pThis) ThisPlusOne;
        pThis->ArrayVariable = (int*)(pThis+1);
        return pThis;
}

以此类推,如果有多个ArrayVariable,可按相同思路进行设置。