通过构造函数的初始化列表初始化数组或向量

3

如何在C++中使用构造函数初始化列表来初始化(字符串)数组或向量?

请考虑以下示例,其中我想使用传递给构造函数的参数来初始化字符串数组:

#include <string>
#include <vector>

class Myclass{
           private:
           std::string commands[2];
           // std::vector<std::string> commands(2); respectively 

           public:
           MyClass( std::string command1, std::string command2) : commands( ??? )
           {/* */}
}

int main(){
          MyClass myclass("foo", "bar");
          return 0;
}

此外,在创建对象时保存两个字符串,哪种类型(array vs vector)更受推荐?为什么?

4
请使用花括号,就像您通常会做的那样。 - chris
@chris:是指 Myclass m = {"hello", "world"}; 还是指 Myclass(const std::string& c1, const std::string& c2) : commands{c1, c2}{} - thokra
@thokra,其中一个不会初始化成员,而另一个在Vaughn的答案中显示得很好。 - chris
@chris:是的,那就是我想表达的意思。 ;) - thokra
4个回答

12

使用C++11,您可以这样做:

class MyClass{
           private:
           std::string commands[2];
           //std::vector<std::string> commands;

           public:
           MyClass( std::string command1, std::string command2)
             : commands{command1,command2}
           {/* */}
};

对于 C++11 之前的编译器,你需要在构造函数中初始化数组或向量:

class MyClass{
           private:
           std::string commands[2];

           public:
           MyClass( std::string command1, std::string command2)
           {
               commands[0] = command1;
               commands[1] = command2;
           }
};
或者
class MyClass{
           private:
           std::vector<std::string> commands;

           public:
           MyClass( std::string command1, std::string command2)
           {
               commands.reserve(2);
               commands.push_back(command1);
               commands.push_back(command2);
           }
};

谢谢。那么对于旧编译器呢? - fotinsky
@fotinsky:我已经扩展了我的答案,以涵盖C++11之前的编译器。 - Vaughn Cato
@VaughnCato,如果我使用C++11编译器并像您在C++之前的示例中定义私有成员std::vector<std::string> commands;,那么有没有更快的方法来初始化commands - Leo Fang
@leofang 是的。无论哪种方式,它都完全相同。 - Vaughn Cato

1
class Myclass{
private:
    Vector<string> *commands;
    // std::vector<std::string> commands(2); respectively 

    public:
    MyClass( std::string command1, std::string command2)
    {
        commands.append(command1);  //Add your values here
    }
}

1
在初始化列表中,您可以调用要初始化成员所属类的任何构造函数。查看 std::stringstd::vector 的文档,并选择适合您的构造函数。
对于存储两个对象,我建议使用 std::pair。但是,如果您预计数量可能会增加,std::vector 是最好的选择。

1
你可以使用


#include <utility>

...
std::pair<string, string> commands;
commands=std::make_pair("string1","string2");

...
//to access them use
std::cout<<commands.first<<" "<<commands.second;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接