如何初始化字符串数组的char指针数组c ++
Posted
技术标签:
【中文标题】如何初始化字符串数组的char指针数组c ++【英文标题】:how to initialize a char pointer array for an array of strings c++ 【发布时间】:2015-03-05 19:14:54 【问题描述】:所以我必须填写一个单词数组,以便稍后访问它们。例如:名词 = "boy", "girl", "house" 等。问题是我必须使用字符点数组。我已经尝试过了,但是它抛出了一个错误,说错误太多初始值设定项。这是代码
class Sentence
private:
char* article[sz];
char* verb[sz];
char* preposition[sz];
char* noun[sz];
后来我像这样调用构造函数,但它没有填充它们。
Sentence::Sentence()
article[10] = "the", "a", "one", "some", "any" ;
verb[] = "drove", "jumped", "ran", "walked", "skipped" ;
preposition[] = "to", "from", "over", "under", "on" ;
noun[] = "boy ", "girl", "dog", "town", "car" ;
【问题讨论】:
sz 在哪里定义? @Perrin Hawver 何时何地设置 sz? 另外,您正在尝试静态初始化数组中的索引。那没有意义。去掉 10 和方括号。 sz 设置在程序的顶部,尽管我将其硬编码为 5,但它会抛出相同的错误。 @PerrinHawver 如果您要在这里提出此类问题,您应该提供MVCE 并在您的问题中发布确切的错误消息。 【参考方案1】:你说:
我必须填写一个单词数组,以便稍后访问它们。
如果这是核心要求,最好使用std::vector<std::string>
而不是char*
的数组。
class Sentence
public:
Sentence();
private:
std::vector<std::string> articles;
std::vector<std::string> verbs;
std::vector<std::string> prepositions;
std::vector<std::string> nouns;
;
您可以使用以下方法初始化成员:
Sentence::Sentence() : articles "the", "a", "one", "some", "any" ,
verbs "drove", "jumped", "ran", "walked", "skipped" ,
prepositions "to", "from", "over", "under", "on" ,
nouns "boy ", "girl", "dog", "town", "car"
您只需在成员变量上使用push_back
即可将项目添加到集合中。
【讨论】:
【参考方案2】:如果sz
是一些常数,那么你可以写
#include <array>
//...
const size_t sz = 5;
class Sentence
private:
std::array<const char *, sz> article;
std::array<const char *, sz> verb;
std::array<const char *, sz> preposition;
std::array<const char *, sz> noun;
//...
Sentence::Sentence()
article = "the", "a", "one", "some", "any" ;
verb = "drove", "jumped", "ran", "walked", "skipped" ;
preposition = "to", "from", "over", "under", "on" ;
noun = "boy ", "girl", "dog", "town", "car" ;
否则,您可以使用 std::vector<const char *>
代替数组。
#include <vector>
//...
class Sentence
private:
std::vector<const char *> article;
std::vector<const char *> verb;
std::vector<const char *> preposition;
std::vector<const char *> noun;
//...
Sentence::Sentence()
article = "the", "a", "one", "some", "any" ;
verb = "drove", "jumped", "ran", "walked", "skipped" ;
preposition = "to", "from", "over", "under", "on" ;
noun = "boy ", "girl", "dog", "town", "car" ;
【讨论】:
【参考方案3】:如果你需要初始化这种固定大小的数组,你可以在构造函数的成员初始化列表中进行。在构造函数的主体中是不可能这样做的。
假设sz
被声明为例如
static const size_t sz = 10;
您使用此语法使用构造函数初始化它们
Sentence::Sentence()
: article "the", "a", "one", "some", "any"
, verb "drove", "jumped", "ran", "walked", "skipped"
, preposition "to", "from", "over", "under", "on"
, noun "boy ", "girl", "dog", "town", "car"
或者考虑使用弗拉德的回答中提到的std::array<char,sz>
,甚至是R. Sahu 提到的std::vector<std::string>
。其中任何一个都应该接受这个初始化器语法。
【讨论】:
以上是关于如何初始化字符串数组的char指针数组c ++的主要内容,如果未能解决你的问题,请参考以下文章