2014-01-24 9 views
0

하단의 코드를 컴파일하는 데 문제가 있습니다. 항상 C로하고 있지만, 반 내면 C++에서 할 수 없습니다. 누군가가 나에게 여기 계신 것을 나에게 깨달을 수 있습니까?클래스 내부에서 구조체를 정의하는 방법은 무엇입니까?

class Parser { 

    struct table { 
    string first; 
    string second; 
    string third; 
    } c_table [] = { 
    "0","a","b", 
    "0","c","d", 
    "0","e","f", 
    }; 
}; 

int main() { 

    return 0; 
} 

test.cpp:22:3: error: too many initializers for ‘Parser::table [0]’ 
test.cpp:22:3: error: could not convert ‘(const char*)"0"’ from ‘const char*’ to ‘Parser::table’ 
test.cpp:22:3: error: could not convert ‘(const char*)"a"’ from ‘const char*’ to ‘Parser::table’ 
test.cpp:22:3: error: could not convert ‘(const char*)"b"’ from ‘const char*’ to ‘Parser::table’ 
test.cpp:22:3: error: could not convert ‘(const char*)"0"’ from ‘const char*’ to ‘Parser::table’ 
test.cpp:22:3: error: could not convert ‘(const char*)"c"’ from ‘const char*’ to ‘Parser::table’ 
test.cpp:22:3: error: could not convert ‘(const char*)"d"’ from ‘const char*’ to ‘Parser::table’ 
test.cpp:22:3: error: could not convert ‘(const char*)"0"’ from ‘const char*’ to ‘Parser::table’ 
test.cpp:22:3: error: could not convert ‘(const char*)"e"’ from ‘const char*’ to ‘Parser::table’ 
test.cpp:22:3: error: could not convert ‘(const char*)"f"’ from ‘const char*’ to ‘Parser::table’ 
+1

문제 발생은 전체 오류를 포함해야 함을 의미합니다. – chris

+0

C++ 11을 사용하고 있습니까? – jrok

+0

@chris : 오류 – Mark

답변

7

사전 C++ 11은 (정수형의 static const 회원 제외) 클래스 정의 내부 구성원을 초기화 할 수 없습니다 있습니다. 이렇게하면 생성자의 본문 안에 채울 수 밖에 없습니다. C에서

은 당신이 초기화를 할 수 있습니다 11 + +하지만

  • 당신은 각 배열 요소에 대해 괄호의 또 다른 세트를 추가해야하고
  • 당신은 배열의 크기를 지정해야합니다

#include <string> 
using std::string; 

class Parser { 

    struct table { 
    string first; 
    string second; 
    string third; 
    } c_table [3] = { 
    {"0","a","b"}, // <-- note the braces 
    {"0","c","d"}, 
    {"0","e","f"} 
    }; 
}; 

Live Example

크기를 지정해야하는 이유는 클래스 정의의 이니셜 라이저가 다른 구성 요소 개수를 가질 수있는 일부 생성자 내부의 멤버 이니셜 라이저에 의해 트럼프 될 수 있기 때문이라고 생각합니다.

관련 문제