在构造函数的初始化列表上初始化数组或向量

fot*_*sky 3 c++ arrays constructor initialization vector

如何在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;
}
Run Code Online (Sandbox Code Playgroud)

除此之外,建议在创建对象时保存两个字符串的两种类型(数组与向量)中的哪一种,为什么?

Vau*_*ato 11

使用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}
           {/* */}
};
Run Code Online (Sandbox Code Playgroud)

对于pre-C++ 11编译器,您需要在构造函数的主体中初始化数组或向量:

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

           public:
           MyClass( std::string command1, std::string command2)
           {
               commands[0] = command1;
               commands[1] = command2;
           }
};
Run Code Online (Sandbox Code Playgroud)

要么

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);
           }
};
Run Code Online (Sandbox Code Playgroud)