Home  >  Article  >  Backend Development  >  Can Arrays Be Initialized in a Constructor's Member Initializer List?

Can Arrays Be Initialized in a Constructor's Member Initializer List?

DDD
DDDOriginal
2024-11-18 11:21:02395browse

Can Arrays Be Initialized in a Constructor's Member Initializer List?

Member Array Initialization in Constructors

Consider the following C class:

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

The code attempts to initialize the arr array member in the constructor's member initializer list. However, it fails to compile.

Questions:

  1. Is it possible to initialize an array in a constructor's member initializer list?
  2. What does the C 03 standard state about this situation?
  3. Does C 11 list initialization address this issue?

Answers:

1. Array Initialization in Constructors

Yes, it is possible to initialize an array in a constructor's member initializer list. However, it requires an intermediary structure:

struct A {
    int foo[3];
    A(int a, int b, int c) : foo{a, b, c} {}
};

class C {
public:
    C() : foo(A(1, 2, 3)) {}
private:
    A foo;
};

2. C 03 Standard

The C 03 standard does not explicitly address the initialization of arrays in member initializer lists. However, the general rules of direct initialization forbid initializing an array with braces.

3. C 11 List Initialization

C 11 introduced list initialization, which allows direct initialization of arrays using braces:

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

In this case, the syntax using braces directly after the array name is valid and initializes the array in the constructor's member initializer list.

The above is the detailed content of Can Arrays Be Initialized in a Constructor's 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