我知道你可以使用列表语法来初始化结构:
struct Foo f = {a, b, c};
return f;
是否可以像使用类和构造函数一样在一行中完成此操作?
最佳答案
如果您希望您的结构保持为 POD ,使用创建它的函数:
Foo make_foo(int a, int b, int c) {
Foo f = { a, b, c };
return f;
}
Foo test() {
return make_foo(1, 2, 3);
}
使用 C++0x uniform initialization消除了对该功能的需求:
Foo test() {
return Foo{1, 2, 3};
// or just:
return {1, 2, 3};
}
关于c++ - 在 C++ 中的一行中初始化并返回一个结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3080278/