C++ 奇怪的类复制

  程序填空,使其输出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’

  • 10
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ann's Blog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值