Initializing Array Members in Constructor Initializer Lists
The inability to initialize arrays in constructors using member initializer lists raises questions regarding the underlying rules and possible solutions.
C++03 Standard and Aggregate Initialization
The C++03 standard prohibits the use of direct initialization for aggregate types, including arrays, in member initializer lists. Direct initialization refers to using the constructor directly with parentheses, as seen in the provided code snippets.
Boost::array as a Solution
An alternative approach is to use a struct that encapsulates the array. By defining a constructor within the struct, you can initialize the array upon object creation. This is similar to the approach taken by the Boost::array library.
C++11 List Initialization
C++11 introduced list initialization, which allows for direct initialization of aggregates, including arrays, in member initializer lists. However, the syntax mentioned in the question is incorrect. To use list initialization, you must enclose the array elements within braces:
class C { public: C() : arr{1, 2, 3} {} };
This syntax correctly initializes the arr array within the constructor.
Atas ialah kandungan terperinci Bolehkah C Constructors Memulakan Tatasusunan Terus dalam Senarai Pemula Ahli?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!