2014-01-24 67 views
0

我無法編譯底部的代碼。我這樣做是C所有的時間,但是當它是一個類中不能做到這一點在C++。有人能告訴我這裏有什麼問題嗎?如何在類中定義struct?

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你不能初始化類定義中的成員(除了整型static const成員)++ 11。這讓你別無選擇,只能將它填充到構造函數的主體中。

在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

我認爲你需要指定尺寸的原因是因爲從類定義的初始化可以通過一些構造函數中成員的初始化,這可能有不同的元素計數來壓倒了。