程序填空,使其输出9 22 5。
#include <iostream>
using namespace std;
class Sample {
public:
int v;
// 在此处补充你的代码
};
void PrintAndDouble(Sample o)
{
cout << o.v;
cout << endl;
}
int main()
{
Sample a(5);
Sample b = a;
PrintAndDouble(b);
Sample c = 20;
PrintAndDouble(c);
Sample d;
d = a;
cout << d.v;
return 0;
}
输入
无
输出
9
22
5
样例输入
样例输出
9
22
5
答案
Sample(int n=0)
{
v=n;
}
Sample(const Sample &x)
{
v=x.v+2;
}
补充:
完整代码
#include <iostream>
using namespace std;
class Sample {
public:
int v;
Sample(int n=0)
{
v=n;
}
Sample(const Sample &x)
{
v=x.v+2;
}
};
void PrintAndDouble(Sample o) //作为函数参数时候会调用复制构造函数
{
cout << o.v;
cout << endl;
}
int main()
{
Sample a(5);
Sample b = a;
PrintAndDouble(b);
Sample c = 20;
PrintAndDouble(c);
Sample d;
d = a;
cout << d.v;
return 0;
}
本来我写的答案是
Sample(int n=0)
{
v=n;
}
Sample(Sample &x)
{
v=x.v+2;
}
然后就华丽丽的报错了:
In function ‘int main()’:
这种编译提示是gcc/g++的一种问题描述格式,告诉你编译问题出现在源代码什么位置,问题出在int main()函数中,接下来是相应的错误(警告)描述。
error: invalid initialization of non-const reference of type ‘Sample&’ from an rvalue of type ‘Sample’ Sample c = 20;
note: initializing argument 1 of ‘Sample::Sample(Sample&)’ Sample (Sample &x)
note: after user-defined conversion: Sample::Sample(int) Sample(int n)
这三条都是说传递的参数类型不对。
题目中多次调用复制构造函数,每次复制构造函数都会生成临时变量。由于复制构造函数的声明中,参数是Sample &,不是常量引用,因为c++编译器的一个关于语义的限制。如果一个参数是以非const引用传入,c++编译器就有理由认为程序员会在函数中修改这个值,并且这个被修改的引用在函数返回后要发挥作用。但如果你把一个临时变量当作非const引用参数传进来,由于临时变量的特殊性,程序员并不能操作临时变量,而且临时变量随时可能被释放掉,因此c++编译器加入了临时变量不能作为非const引用的这个语义限制。
更多参考:C++之invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’