在C++中初始化并返回一行结构

Joh*_*n C 12 c++ struct

这可能吗?

我知道您可以使用列表语法初始化结构.

IE

struct Foo f = { a, b, c};
return f;
Run Code Online (Sandbox Code Playgroud)

有可能像在类和构造函数中那样在一行中执行此操作吗?

谢谢

Geo*_*che 27

如果您希望结构保持为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);
}
Run Code Online (Sandbox Code Playgroud)

使用C++ 0x 统一初始化消除了对该函数的需求:

Foo test() {
    return Foo{1, 2, 3};
    // or just: 
    return {1, 2, 3};
}
Run Code Online (Sandbox Code Playgroud)

  • 在C++ 0x中,您甚至可以"返回{1,2,3};" (6认同)
  • @Cubbi:对,好点 - 虽然我认为当我们开始在生产中使用新功能时,我会更喜欢显式版本以避免维护陷阱. (2认同)
  • 如果返回类型本身很复杂,我认为后者可能非常方便:`tuple <X,Y,Z> test(){return/*tuple <X,Y,Z>*/{x,y,z}; }`.(我猜有时结果类型甚至可能令人难以置信的复杂,甚至可能在`decltype`等帮助下确定,在这种情况下,不必再次重复扣除可能是好的:)) (2认同)

Ami*_*hum 14

为结构创建一个构造函数(就像一个类),就这样做

return Foo(a,b,c);
Run Code Online (Sandbox Code Playgroud)

编辑:只是为了澄清:C++中的结构就像类,它们的默认访问权限是公共的(而不是类中的私有).因此,您可以非常简单地创建构造函数,例如:

struct Foo {
  int a;
  Foo(int value) : a(value) {}
};
Run Code Online (Sandbox Code Playgroud)