Bolehkah C Constructors Memulakan Tatasusunan Terus dalam Senarai Pemula Ahli?

Susan Sarandon
Lepaskan: 2024-11-14 12:59:02
asal
454 orang telah melayarinya

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} {}
};
Salin selepas log masuk

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!

sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel terbaru oleh pengarang
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan