2013-02-19 2 views
3

사람들이 초기화 목록의 멤버 변수 뒤에 괄호를 넣는 것을 보았습니다. 사람들이 왜 그렇게했을까요?멤버 변수 다음에 괄호를 넣어서 초기화 하시겠습니까?

class A{ 
public: 
    A(); 
    ... 
private: 
    vector<string> v; 
} 

및 소스 파일 :

A::A() : v() {} 

내 질문은 무엇 V는()이며, 할 이유는 사람들이 이후 그렇게 할 것입니다

예를 들어, 내가 STL 헤더 파일에 용기를 가지고 어떤 것도 v처럼 초기화되지 않습니다.

+1

이 경우 초기화 목록에서 명시 적으로 'v()'를 언급 할 필요가 없습니다. 그러나 목록에서 언급하고 싶다면 괄호를 써야합니다. –

+0

이것을 _value-initialization_이라고합니다. – ildjarn

답변

5

기본 생성자 또는 일반 형식의 이니셜 라이저가 실행됩니다. 이 컨텍스트에서는 벡터를 기본 구성합니다. 기본 생성자이므로 여기서는 필요하지 않습니다. v은 이니셜 라이저가 없으면 기본적으로 생성되었습니다.


차기와 웃음에 대한
class Example { 

private: 
    int defaultInt; 
    vector<int> defaultVector; 
    int valuedInt; 
    vector<int> sizedVector; 

public: 

    Example(int value = 0, size_t vectorLen = 10) 
     : defaultInt(), defaultVector(), valuedInt(value), sizedVector(vectorLen) 
    { 
     //defaultInt is now 0 (since integral types are default-initialized to 0) 
     //defaultVector is now a std::vector<int>() (a default constructed vector) 
     //valuedInt is now value since it was initialized to value 
     //sizedVector is now a vector of 'size' default-intialized ints (so 'size' 0's) 
    } 

}; 

, 당신은 또한 값 valuevector vectorLen을 가진 요소를 얻을 수 thirdVector(vectorLen, value)을 할 수 있습니다. (그래서 Example(5, 10)thirdVector 5을 평가 10 요소의 벡터를 만들 것입니다.)이 때로는 더 명시 적으로 수행

2

My question is what is v() and why do people do that since that doesn't look like v is initialized into a value either

. 비 POD 유형의 경우 기본 생성자가 자동으로 호출되므로 필수는 아닙니다. 형식 기본 생성자가 정의되지 않았거나 액세스 할 수없는 경우 컴파일 오류가 발생합니다.

이 값은 POD 유형이 초기화되지 않은 경우 정의되지 않으므로 POD 유형에 가장 적합합니다.

struct A 
{ 
    int t; 
    A() : { /* value of t undefined */ } 
} 

struct A 
{ 
    int t; 
    A() : t() { /* value of t is t's default value of 0 */ } 
}