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

C++语言 码拜 8年前 (2016-09-12) 1656次浏览
《程序员面试宝典》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++高手,各位项目高手给予一下指导。非常感谢
解决方案

20

类型转换产生的是个临时变量(右值对象)
B& 是左值引用
所以 不匹配
所以没有合适的,构造函数,初始化 形参变量Play 函数的形参对象

20

错误的原因是临时对象无法绑定到非常量左值引用上。
题主看点好书吧,例如 c++ primer。

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明拷贝构造函数的形参不加const时遇到的情况
喜欢 (0)
[1034331897@qq.com]
分享 (0)