gpt4 book ai didi

c++11 - 使用统一初始化调用复制构造函数

转载 作者:行者123 更新时间:2023-12-03 08:23:35 25 4
gpt4 key购买 nike

我试图通过统一初始化调用默认复制构造函数,但它不起作用。

例如:

#include <string>

struct Work {
std::string author;
std::string name;
int year;
};

int main() {
Work s9 {"Beethoven", "Symphony No. 9 in D minor, Op. 125; Choral", 1824}; // memberwise initialization
Work currently_playing {s9}; // copy initialization

return 0;
}

我将其编译为:g++ -std=c++11 -c Ex1.cpp

编译器报错:

Ex1.cpp: In function ‘int main()’:
Ex1.cpp:11:28: error: could not convert ‘s9’ from ‘Work’ to ‘std::string {aka std::basic_string<char>}’
Work currently_playing {s9}; // copy initialization
^

统一初始化不能复制初始化对象吗?

最佳答案

这是 C++11 标准中的错误。 C++14 改变了列表初始化的执行方式。在 C++11 中,如果 Xaggregate typeX{X{}} 将执行聚合初始化 . C++14 添加了一个额外的子句,以便此代码正确调用相应的构造函数; [dcl.init.list]/3.2:

If T is an aggregate class and the initializer list has a single element of type cv U, where U is T or a class derived from T, the object is initialized from that element (by copy-initialization for copy-list-initialization, or by direct-initialization for direct-list-initialization).

来源:

http://eel.is/c++draft/dcl.init.list#3.2

http://en.cppreference.com/w/cpp/language/list_initialization#Explanation

关于c++11 - 使用统一初始化调用复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46339519/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com