是否有像C#中的C++新声明

Jim*_*988 4 c++ c++11 c++14

我想知道newC#中是否有类似C++ 的声明

C#允许你这样做,它只是稍微加密了代码:

FuncCall( new Foo() {
    Bar = "sausage",
    Boo = 4
} );
Run Code Online (Sandbox Code Playgroud)

我只是觉得这在C++中有点草率:

unique_ptr<Foo> foo( new Foo() );
foo.Bar = "sausage";
foo.Boo = 4;

FuncCall( move( foo ) );
Run Code Online (Sandbox Code Playgroud)

Foo可能看起来像这样:

class Foo
{
public:
    Foo();

    string Bar;
    int Boo;
}
Run Code Online (Sandbox Code Playgroud)

为什么我不只是将所有内容放入构造参数中?

因为当你必须这么多时,这是愚蠢的:

Foo( int width, int height, string title, string className, string thjis, stihjrjoifger gfirejgoirejgioerjgoire ) 它一直在继续......虽然我已经拥有了我班级内的属性......所以只是想知道它是否可以完成..

Dan*_*rey 6

你可以使用lambda:

FuncCall( []{ Foo f; f.Bar = "sausage"; f.Boo = 4; return f; }() );
Run Code Online (Sandbox Code Playgroud)

实例