首頁 > 後端開發 > C++ > 主體

C 建構函式可以直接在成員初始化列表中初始化陣列嗎?

Susan Sarandon
發布: 2024-11-14 12:59:02
原創
454 人瀏覽過

Can C++ Constructors Initialize Arrays Directly in Member Initializer Lists?

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板