문제

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