开发者

Only static and const variables can be assign to a class?

I am learning C开发者_StackOverflow++. Just curious, can only static and constant varibles be assigned a value from within the class declaration? Is this mainly why when you assign values to normal members, they have a special way doing it

void myClass::Init() : member1(0), member2(1)
{
}


This looks like it is supposed to be a constructor; if it is, it should have no return type, and it needs to have the same name as the class, e.g.,

myClass::myClass()
    : member1(0), member2(1)
{

}

Only a constructor can have an initializer list; you can't delegate that type of initialization to an Init function.

Any nonstatic members can be initialized in the constructor initializer list. All const and reference members must be initialized in the constructor initializer list.

All things being equal, you should generally prefer to initialize all members in the constructor initializer list, rather than in the body of the constructor (sometimes it isn't possible or it's clumsy to use the initializer list, in which case, you shouldn't use it, obviously).


Static class members don't belong to any particular object. A static member is shared between all objects of that class. Therefore, you don't initialize them in a constructor - that would re-initialize them far too often, for instance.

Now there is the question why only static const class members can be initialized in the class itself. The reason is that the class is most likely in a header, and that header is included in multiple translation units. This causes a problem for the compiler. In which translation unit (ie. in which object file) should it put the actual initialization? But for simple consts, it doesn't matter. int const TWO = 2; doesn't need an actual initialization in a translation unit, the compiler just remembers it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜