如何初始化字符串数组c ++的char指针数组

时间:2015-03-05 19:14:55

标签: c++ arrays initialization

所以我必须填写一系列单词,以便我以后可以访问它们。例如:名词= {“boy”,“girl”,“house”}等等。麻烦的是我必须使用char点数组。我试过这个,但它抛出一个错误,说错误太多的初始化值。这是代码

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" };
}

3 个答案:

答案 0 :(得分: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即可向集合中添加项目。

答案 1 :(得分:0)

如果需要初始化此类固定大小的数组,可以在构造函数的成员初始化列表中执行此操作。在构造函数的主体中不可能这样做。

假设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" } {
}

或者考虑使用Vlad的回答中提到的std::array<char,sz>,或者甚至是R. Sahu提到的std::vector<std::string>。其中任何一个都应该接受这个初始化语法。

答案 2 :(得分:0)

如果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" };
}