-4

我很好奇现代 c++ 标准人们是否考虑或添加了 C# 的“对象初始化器”语法。例如,在 C# 中,我可以在初始化期间像这样初始化对象的成员:

StudentName student2 = new StudentName
{
    FirstName = "Craig",
    LastName  = "Playstead"
};

public class StudentName {
    public string FirstName;
    public string LastName;
};

如果标准人们计划将“对象初始化器”语法添加到现代 C++ 中,那将非常方便,即。C++11、C++14、C++17、C++20等...

它目前是否存在于现代 C++ 规范中?

4

1 回答 1

5

看看指定的初始化程序。它们自 C99 以来一直存在于 C 中,但并未添加到 C++ 中。现在计划在 C++20 中添加它们,但有一些限制。例子:

struct db_config
{
    std::string host = "localhost";
    std::string port = "5432";
    std::string dbname;
    std::string user;
    std::string password;
} config = {
    .dbname = "test",
    .user = "admin",
    .password = "v3ry$3cur3"
};

然而,一些编译器(例如 GCC)已经允许在 C++ 代码中使用 C 指定的初始值设定项作为扩展。

于 2018-07-16T16:52:56.550 回答