西贝明。。。。。。 2022-03-17 14:41 采纳率: 66.7%
浏览 39
已结题

输出流重载的参数引用

下面代码正常运行
#include
using namespace std;
class Person
{
public:
Person(int age=0)
{
m_age = new int(age);
}

~Person()
{
    if (m_age != NULL)
    {
        delete m_age;
        m_age = NULL;
    }
}
friend ostream& operator<<(ostream& output, Person &p);
Person& operator=(Person& p);

private:
int* m_age;
};
ostream& operator<<(ostream& output, Person &p)
{
output << *p.m_age;
return output;
}
Person& Person:: operator=(Person& p)
{

if (m_age != NULL)
{
    delete m_age;
    m_age = NULL;
}

m_age = new int(*p.m_age);
return *this;

}
void test01()
{
Person p1(19), p2(20);
p2 = p1;
cout << "p1=" << p1 << endl;
cout << "p2=" << p2 << endl;
}
int main()
{
test01();
}
可如果把输出流重载函数里第二个参数里的&去掉,代码就会出错

img


能给我解释一下为什么吗🙏

  • 写回答

2条回答 默认 最新

  • _GX_ 2022-03-17 15:03
    关注

    当你去掉参数中&时,参数是按值拷贝,由于你没有实现拷贝构造函数,编译器会自动生成默认的拷贝构造函数,默认的拷贝构造函数只是简单地按位拷贝,即把成员变量指针m_age直接拷贝过去,这样实参和形参两个对象同时拥有m_age指针,当对象析构时,它们就试图释放m_age指针所指的内存,这就造成了对m_age指针释放两次错误。

    解决这个问题,你可以添加自己的拷贝构造函数、或移动构造函数

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 3月25日
  • 已采纳回答 3月17日
  • 创建了问题 3月17日

悬赏问题

  • ¥15 R运行没有名称为"species"的插槽对于此对象类"SDMmodelCV"
  • ¥20 基于决策树的数字信号处理,2ask 2psk 2fsk的代码,检查下报错的原因
  • ¥20 python作业求过程
  • ¥15 wincc已组态的变量过多
  • ¥60 如图:直线与椭圆X轴平行,求直线与椭圆任意一点的相切坐标计算公式
  • ¥50 如何用python使用opencv里的cv::cudacodec::VideoWriter函数对视频进行GPU硬编码
  • ¥100 c#solidworks 二次开发 工程图自动标边线法兰 等折弯尺寸怎么标
  • ¥15 halcon DrawRegion 提示错误
  • ¥15 FastAPI Uvicorn启动显示404
  • ¥15 centos7.9脚本,怎么排除特定的访问记录