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
Release: 2024-11-29 02:07:08
Original
543 people have browsed it

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];
};
Copy after login

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};
Copy after login

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];
};
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template