在构造函数的初始化列表上初始化数组或向量
Initialize array or vector over constructor's initializing list
如何使用构造函数的初始化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::string
和std::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
}
}
相关文章:
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 在函数内部的声明中初始化数组,并在外部使用它
- 为什么用结构初始化数组需要指定结构名称
- 有没有一种代码密度较低的方法来使用非默认构造函数初始化数组?
- C++使用另一个数组和新值初始化数组
- 初始化数组、"memset"或" {//value} "的最佳方法是什么?
- 在 constexpr 构造函数中初始化数组是否合法?
- 我可以初始化 const 实例,以便我可以将其用作 const 来初始化数组吗?
- 在构造函数中初始化数组
- 是否可以使用函数返回的值初始化数组
- 使用宏使用额外元素初始化数组
- 在循环中显示不同值的初始化数组
- 如何在macOS中的旧扩展clang和gcc编译器中初始化数组和向量
- 使用可变模板列表初始化数组,并放置new
- 使用函数从 Visual Studio 2017 中的 main 创建和初始化数组
- 使用 c++ 中的函数初始化数组
- 这是使用构造函数初始化数组对象的最佳方法吗?
- C++ 使用变量而不是常量表达式初始化数组
- 在初始化列表中初始化数组的更好方法
- 在可变参数模板类中初始化数组