简体   繁体   中英

Short c++ class constructor from brace-enclosed initializer list

The following piece of core works fine:

class A {
public:
    int a;
    int b;
};

A obj{ 1, 2 };

If, however, one adds default constructor explicitly: A(){}, one has to add another one for brace-enclosed initializer list, like:

A(int a, int b):a(a), b(b) {}.

Is there a shorter form like, eg:

A(const A& ab) { *this = ab } ???

The one above doesn't work.

A(int a, int b):a(a), b(b) {}.

Is there a shorter form

No. Other than a few white spaces, this constructor is as short as it can be.

Unfortunately not.

When you created a default constructor, you prevented yourself from initialising the class using aggregate-initialisation.

To be able to get back the ability to use that declaration syntax, you have to create another constructor that takes all the necessary arguments… and there is no shorter way to do that than what you have written.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM