如何在类中定义struct?

时间:2014-01-24 20:58:58

标签: c++

我无法在底部编译代码。我一直在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 个答案:

答案 0 :(得分:7)

Pre-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

我认为你需要指定维度的原因是因为类定义中的初始化程序可以被某个构造函数中的成员初始化程序所取代,这可能具有不同的元素数。