在一个作用域内创建临时对象时,编译器无法看到提供给构造函数的参数并会产生编译错误。
例如,以下代码就会出现这种情况:
#include <sstream>
#include <iostream>
class csventry
{
public:
csventry(std::ostream& ostream) :
_ostream(ostream)
{}
~csventry()
{ _ostream << std::endl; }
csventry& operator << (const std::string& value) {
_ostream << ", ";
_ostream << value;
return *this;
}
private:
std::ostream& _ostream;
};
int main ()
{
std::ostringstream log;
{ csventry(log) << "User Log-on:"; }
{ csventry(log); }
{ csventry(log) << "Summary:"; }
std::cout<<log.str()<<std::endl;
}
我遇到了一个错误。
main.cpp: In function ‘int main()’:
main.cpp:29:16: error: no matching function for call to ‘csventry::csventry()’
{ csventry(log); }
^
main.cpp:7:2: note: candidate: csventry::csventry(std::ostream&)
csventry(std::ostream& ostream) :
^~~~~~~~
main.cpp:7:2: note: candidate expects 1 argument, 0 provided
main.cpp:4:7: note: candidate: constexpr csventry::csventry(const csventry&)
class csventry
^~~~~~~~
main.cpp:4:7: note: candidate expects 1 argument, 0 provided
我尝试使用gcc 7.3和5.4
当我给临时对象命名时,它可以工作,{ csventry entry(log); }
为什么编译器会忽略提供的参数?