拷贝构造函数的形参不加const时遇到的情况
《程序员面试宝典》10.4中的最后一题。
源程序如下:
#include<iostream>
using namespace std;
class B{
private:
int data;
public:
B(int i):data(i){
cout<<"constructed"<<endl;
}
B(B &b){
data=b.data;
cout<<"copy"<<endl;
}
~B(){cout<<"destructed"<<endl;}
};
B play(B b){
return b;
}
int main()
{
play(5);
return 0;
}
问题描述:我自己添加了拷贝构造函数(但是形参没有加const),然后这样编译就会报错。报错如下:
destructed.cpp: In function ‘int main()’:
destructed.cpp:26:8: error: no matching function for call to ‘B::B(B)’
play(5);
^
destructed.cpp:26:8: note: candidates are:
destructed.cpp:13:2: note: B::B(B&)
B(B &b){
^
destructed.cpp:13:2: note: no known conversion for argument 1 from ‘B’ to ‘B&’
destructed.cpp:10:2: note: B::B(int)
B(int i):data(i){
^
destructed.cpp:10:2: note: no known conversion for argument 1 from ‘B’ to ‘int’
destructed.cpp:19:3: error: initializing argument 1 of ‘B play(B)’
B play(B b){
^
但是如果加上const就可以了。查找问题的时候,发现有一个概念是:转换构造函数的概念(只有一个参数,且这个参数不是本类的const引用时,就是转换构造函数),不知道是不是对这个结果有影响。
现在,我就很纠结为什么加上const,就能够编译成功,不加const就编译错误?已经查了很多内容,却都没有这相关的知识点,所以就来求助各位c++大神,各位项目大神给予一下指导。非常感谢