拷贝构造函数的形参不加const时遇到的情况

cwtlps cwtlps 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
《程序员面试宝典》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++大神,各位项目大神给予一下指导。非常感谢
...全文

相关推荐

评论 8
收藏 已收藏
分享
返回顶部
cwtlps
C++ 语言 65,213 成员 250,513 内容