C++11提供了新的初始化struct和class属性的方法,但是仅能初始化公有成员变量。
代码如下:
#include <iostream>
#include <map>
using namespace std;
class Test {
public: // private和protected 下面的初始化方式不可用
uint32_t a;
uint64_t b;
uint64_t c;
std::string d;
std::string f;
std::map<string, string> g;
};
int main(int argc, char *argv[]) {
Test test = {
.a = 1,
.b = 2,
.c = 3,
.d = "str",
.f = "str2",
.g = { {"key", "value"}, {"key", "value"}, {"key2", "value2"} }
};
//验证输出:
std::cout << test.a << std::endl;
std::cout << test.b << std::endl;
std::cout << test.c << std::endl;
std::cout << test.d << std::endl;
std::cout << test.f << std::endl;
for (auto& elem : test.g) {
std::cout << elem.first << " -- " << elem.second << std::endl;
}
}
输出结果:
1
2
3
str
str2
key -- value
key2 -- value2