拷贝构造函数的形参不加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++大神,各位项目大神给予一下指导。非常感谢
源程序如下:
#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++大神,各位项目大神给予一下指导。非常感谢
...全文
相关推荐
C++程序员面试题集
关于C++基础的文档,其中有大量关于C++面试过程中所有的题目。
F1F9BAAC766B88BF.pdf
F1F9BAAC766B88BF.pdf
拷贝构造函数
简单而又复杂的拷贝构造函数,为初学者及急需作业这提供帮助,急人之所急
类对象作为函数形参[可运行源码]
本文介绍了在C++编程中,类对象作为函数形参的使用方法及其效率问题。文章指出,类对象作为形参时,默认会调用拷贝构造函数,可能导致性能下降。为了提高效率,建议使用引用类型作为形参,并在不需要修改形参内容时加上const修饰。文章还提供了一个具体的编程任务,要求编写一个output函数,以Int的常引用作为形参,输出其成员变量的值。任务涉及Int.h、Int.cpp和main.cpp三个文件,其中Int.h和main.cpp不得修改,用户需在Int.cpp中完成output函数的实现。
C++友元函数与拷贝构造函数详解
主要介绍了C++友元函数与拷贝构造函数,需要的朋友可以参考下


