c++ 初始化静态static成员变量或static复合成员变量
https://stackoverflow.com/questions/185844/how-to-initialize-private-static-members-in-c
One idiom was proposed at: https://stackoverflow.com/a/27088552/895245 but here goes a cleaner version that does not require creating a new method per member, and a runnable example:
#include <cassert> #include <vector> // Normally on the .hpp file. class MyClass { public: static std::vector<int> v, v2; static struct _StaticConstructor { _StaticConstructor() { v.push_back(1); v.push_back(2); v2.push_back(3); v2.push_back(4); } } _staticConstructor; }; // Normally on the .cpp file. std::vector<int> MyClass::v; std::vector<int> MyClass::v2; // Must come after every static member. MyClass::_StaticConstructor MyClass::_staticConstructor; int main() { assert(MyClass::v[0] == 1); assert(MyClass::v[1] == 2); assert(MyClass::v2[0] == 3); assert(MyClass::v2[1] == 4); }
See also: static constructors in C++? I need to initialize private static objects
Tested with g++ -std=c++11 -Wall -Wextra
, GCC 7.3, Ubuntu 18.04.
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
支付宝扫一扫捐赠
支付宝扫一扫捐赠
微信公众号: 共鸣圈
欢迎讨论,邮件: 924948$qq.com 请把$改成@
QQ群:263132197
QQ: 924948