通过 new 运算符初始化结构的问题

ale*_*lex 6 c++ new-operator c++11

以下是我的程序的两个变体

struct customer{
    char fullname[35];
    double payment;
};

int main()
{
    customer alex{"Alex", 15};
    return 0;
}
Run Code Online (Sandbox Code Playgroud)
struct customer{
    char fullname[35];
    double payment;
};

int main()
{
    customer* alex = new customer {"Alex", 15};
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

第一个工作正常,但第二个引发error:could not convert '{"Alex", 15}' from 'brace-enclosed initializer list' to 'customer'. 有什么问题?

Aco*_*orn 3

我认为代码很好,但有些编译器可能会抱怨。

尝试改为:

customer* alex = new auto(customer{"Alex", 15});
Run Code Online (Sandbox Code Playgroud)

  • 这会在堆栈上创建对象,然后调用复制构造函数,不是吗? (3认同)