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

Initialize array or vector over constructor's initializing list

本文关键字:初始化 数组 向量 列表 构造函数      更新时间:2023-10-16

如何使用构造函数的初始化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;
}
除此之外,建议

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

使用 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);
           }
};

在初始值设定项列表中,可以调用要初始化的成员的类的任何构造函数。查看std::stringstd::vector文档,并选择适合您的构造函数。

为了存储两个对象,我建议使用 std::pair .但是,如果您预计该数字可能会增长std::vector是最佳选择。

你可以使用

#include <utility>
...
std::pair<string, string> commands;
commands=std::make_pair("string1","string2");
...
//to access them use
std::cout<<commands.first<<" "<<commands.second;
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
    }
}