سؤال

I was trying to use brace-initialization (which thankfully Visual Studio 2013 actually supports), but for some reason when I do it on a class, it requires two sets of braces. For example:

class NumberGrabber {
    int number;
public:
    NumberGrabber() : number{ 5 }{}

    int getNumber() { return number; }
};

Why does it require me to say number { 5 }{}? That doesn't really make visual sense to me.

هل كانت مفيدة؟

المحلول

The former set of braces is the initializer for number, the latter is the compound statement that defines the body of the constructor. With proper formatting, this may become clearer.

NumberGrabber()
    : number{5}
{
}

Does that make more sense?

نصائح أخرى

In C++11 you can also do

#include <iostream>

// look ma, no {}
class NumberGrabber {
    int number = 5;
public:
    int getNumber() { return number; }
};

int main()
{
    std::cout << NumberGrabber().getNumber() << "\n";    
}

Live example (works for clang and g++) that prints 5.

A constructor is a function, and a function definition needs a body. {} is an empty function body.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top