Home>
The problem i am having

I don't know if the initialization method is correct.

Source code
class A {
    public:
        int i;
        const int j;
    private: private:
        int k;
};
int main () {
    A a {.i = 10,
        .j = 10,
        .k = 10
    };
    return 0;
}
What I tried

I checked it with cpprefjp.
(Maybe it has something to do with uniform initialization?)
And I compiled something like the source code above.
I got an error at k because it was private.

What i want you to tell me

About i, j, k in the above source code,
I don't know which one is grammatically correct in C ++.
And if correct, objects such as std :: string
Can it be initialized?
I have a professor.

Supplementary information (FW/tool version, etc.)

windows10
g ++ 9.2.0
Compile optionsg ++ hoge.cpp -o hoge -Wall -Wextra -std = c ++ 1z

c++
  • Answer # 1

    The instructional initializer seems to be a function from c ++ 20, so in c ++ 17, it is wrong to say whether it is grammatically correct.
    https://ja.cppreference.com/w/cpp/language/aggregate_initialization

    Instructed initialization is included as an extension of gcc, so the code in the title probably didn't cause any errors other than private.
    To make the extension error, add the -pedantic-errors option.

    Private initialization is not possible with this initialization method. Because it's private ...
    I think that private can only be initialized with a constructor etc. (because it is private for that).
    Of course, objects such as stirng can also be initialized.

  • Answer # 2

    Let's use the constructor.

    class A
    {
    public:
       A (): i (10), j (10), k (10) {}
    };