Home > Backend Development > C++ > body text

How to Initialize a Constant Array in a Class Initializer in C ?

Patricia Arquette
Release: 2024-11-06 03:44:02
Original
325 people have browsed it

How to Initialize a Constant Array in a Class Initializer in C  ?

Initializing a Constant Array in a Class Initializer in C

In C , initializing a constant array within a class's initializer list requires a slightly different approach than initializing other member variables. Let's explore the case where the constant array is meant to have instance-specific values.

Consider the following class:

<code class="cpp">class a {
public:
    const int b[2];
};</code>
Copy after login

To initialize b with specific values in the constructor initialization list, use the following syntax:

<code class="cpp">a::a() : b{2, 3} {
    // Other initialization stuff
}</code>
Copy after login

This approach relies on C 11's brace-enclosed initializer list syntax, which allows you to initialize a constant array within the class initializer. Here's an example:

<code class="cpp">struct a {
    const int b[2];

    // Constructor
    a() : b{2, 3} {}
};

int main() {
    a a;
}</code>
Copy after login

In this example, each instance of a will have a unique b array with the specified values. Note that this technique is not available in C 98 or earlier versions.

The above is the detailed content of How to Initialize a Constant Array in a Class Initializer in C ?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!