来自《C++编程语言》第四版的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语言中一样将一个结构体赋值给另一个结构体)。因此,程序应该能够编译通过。这是编译器的问题吗?有任何解释吗?