在作用域中创建临时对象时,编译器不会看到构造函数提供的参数并给出编译错误.
如下例所示:
#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;
}
Run Code Online (Sandbox Code Playgroud)
我收到这个错误.
main.cpp: In function ‘int main()’:
main.cpp:29:16: error: no matching function for call to ‘csventry::csventry()’
{ …Run Code Online (Sandbox Code Playgroud)