gpt4 book ai didi

C++成员初始化、复制初始化和默认初始化

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:02:31 29 4
gpt4 key购买 nike

摘自 The C++ Programming Language,第 4 版,“17.3.1 没有构造函数的初始化”部分,第 489 页

书中示例中标记的行无法编译并出现此错误-

$ g++ -std=c++11 ch17_pg489.cpp
ch17_pg489.cpp: In function 'int main()':
ch17_pg489.cpp:32:34: error: could not convert 's9' from 'Work' to 'std::string {aka std::basic_string<char>}'
Work currently_playing { s9 }; // copy initialization

我有 Cygwin

$ g++ --version
g++.exe (tdm64-2) 4.8.1

引用上述部分的文本,

we can initialize objects of a class for which we have not defined a constructor using
• memberwise initialization,
• copy initialization, or
• default initialization (without an initializer or with an empty initializer list).


#include <iostream>

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

/*
// This correctly prints the respective fields
std::cout << s9.author << " | "
<< s9.name << " | "
<< s9.year << std::endl;
*/

// Fails to compile
Work currently_playing { s9 }; // copy initialization

Work none {}; // default initialization

return 0;
}

根据我的理解,复制初始化将由编译器生成的默认复制构造函数提供,或者它只是一个成员明智的复制(将一个结构分配给另一个结构,如在 C 中)。所以程序应该在这里编译。

或者这是编译器的怪癖??

有什么解释吗?

最佳答案

正如您在第 4 版勘误表中所见

http://www.stroustrup.com/4th.html

People have pointed out that the {} doesn't work for copy construction:

X x1 {2};     // construct from integer (assume suitable constructor)
X x2 {x1}; // copy construction: fails on GCC 4.8 and Clang 3.2

I know that. It's a bug in the standard. Fixed for C++14. For now use one of the traditional notations:

X x3(x1);     // copy construction
X x4 = x1; // copy construction

fixed适用于 GCC 4.10

Here's缺陷报告本身。

关于C++成员初始化、复制初始化和默认初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23924339/

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