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.
以上是C 建構函式可以直接在成員初始化列表中初始化陣列嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!