假设您想要一个与类关联的预定义值/对象(const或非const)的静态数组.可能的选项是使用std:vector
,std::array
或C-style array (ie. [])
,或.例如,
在.hpp:
class MyClass {
public:
static const std::vector<MyClass> vec_pre; // No efficient way to construct with initializer list, since it always uses Copy Contructor, even when using std::move
static const std::array<MyClass, 2> arr_pre; // Have to specify size which is inconvenient
static const MyClass carr_pre[]; // Not compatible with C++11 for-range since size is undefined
};
Run Code Online (Sandbox Code Playgroud)
在.cpp
const std::vector<MyClass> MyClass::vec_pre = { std::move(MyClass{1,2,3}), std::move(MyClass{4,5,6}) }; // NOTE: This still uses …
Run Code Online (Sandbox Code Playgroud)