class Sample
{
public:
Sample();
Sample(int i);
Sample(Sample& s);
~Sample();
};
Sample::Sample()
{
cout<<"Default constructor called\n";
}
Sample::Sample(int i)
{
cout<<"1-argument constructor called\n";
}
Sample::Sample(Sample& s)
{
cout<<"Copy constructor called\n";
}
Sample::~Sample()
{
cout<<"Destructor called\n";
}
void Fun(Sample s)
{
}
int main()
{
Sample s1;
Fun(5);
return 0;
}
我预计隐式转换为5。 但是,当我编译上面的代码时,我得到以下错误:
main.cpp:7:8: error: no matching function for call to ‘Sample::Sample(Sample)’
main.cpp:7:8: note: candidates are:
Sample.h:10:3: note: Sample::Sample(Sample&)
Sample.h:10:3: note: no known conversion for argument 1 from ‘Sample’ to ‘Sample&’
Sample.h:9:3: note: Sample::Sample(int)
Sample.h:9:3: note: no known conversion for argument 1 from ‘Sample’ to ‘int’
Sample.h:8:3: note: Sample::Sample()
Sample.h:8:3: note: candidate expects 0 arguments, 1 provided
Helper.h:6:13: error: initializing argument 1 of ‘void Fun(Sample)’
有什么问题?当我删除复制构造函数时,上面的代码编译成功。
提前致谢。
答案 0 :(得分:6)
Temporaries无法绑定到非const引用。你的拷贝构造函数应该是:
Sample::Sample(const Sample&)
删除它会告诉编译器生成一个具有上述签名的普通文件。