初始化数组

如果类具有一个构造函数,某些该类由构造函数初始化。 如果存在初始值设定项的少量项列表大于该数组的元素,默认构造函数剩余的组件。 如果默认构造函数没有为类定义,该初始值设定项列表必须完成的,即必须有每个元素的初始值设定项在数组。

请考虑以下定义了两个构造函数 Point 类:

// initializing_arrays1.cpp
class Point
{
public:
   Point()   // Default constructor.
   {
   }
   Point( int, int )   // Construct from two ints
   {
   }
};

// An array of Point objects can be declared as follows:
Point aPoint[3] = {
   Point( 3, 3 )     // Use int, int constructor.
};

int main()
{
}

使用构造函数 Point( int, int ), aPoint 的第一个元素构造;使用默认构造函数,将保持的两个元素构造。

静态成员数组 (是否 const ) 在其定义可初始化 (在类声明之外)。 例如:

// initializing_arrays2.cpp
class WindowColors
{
public:
    static const char *rgszWindowPartList[7];
};

const char *WindowColors::rgszWindowPartList[7] = {
    "Active Title Bar", "Inactive Title Bar", "Title Bar Text",
    "Menu Bar", "Menu Bar Text", "Window Background", "Frame"   };
int main()
{
}

请参见

参考

使用特殊成员函数的初始化