Home >Backend Development >C++ >How to Initialize an Array Member in a Member Initializer List?

How to Initialize an Array Member in a Member Initializer List?

Barbara Streisand
Barbara StreisandOriginal
2024-11-29 02:07:08621browse

How to Initialize an Array Member in a Member Initializer List?

How to Initialize an Array Member in a Member Initializer List

Introduction

Initializing an array member in a member initializer list can seem like a straightforward task, but can be difficult in practice. This article will explore different approaches and answer common questions related to this topic.

Problem and Code

The following code snippet attempts to initialize an array member in a constructor's initializer list:

class C {
public:
    C() : arr({1,2,3}) //doesn't compile
{}
private:
    int arr[3];
};

However, the code fails to compile. The reason is that arrays can only be initialized using the assignment operator =, such as:

int arr[3] = {1,3,4};

Solutions

  • Use a Struct:

One solution is to use a struct to encapsulate the array, allowing it to be initialized in the constructor. This is essentially what the Boost.Array library does.

  • Use List Initialization:

C 11 introduces list initialization, which can be used to initialize an array in a member initializer list. The following code would work:

class C {
public:
    C() : arr{1, 2, 3} { }
private:
    int arr[3];
};

C 03

The C 03 standard does not specifically address the initialization of aggregates (including arrays) in constructor initializers. The invalidity of the original code is a consequence of the rules for direct initialization, which prohibit the use of initializer lists for arrays.

C 11

C 11's list initialization syntax simplifies the initialization of arrays in member initializer lists. However, it's important to use the correct syntax, as shown above.

The above is the detailed content of How to Initialize an Array Member in a Member Initializer List?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn