C++——拷贝构造和重载的赋值运算符

今天突然被搞蒙,重新复习了一下
多说无益,直接上代码

#include <iostream>
#include <string.h>
using namespace std;
class A
{
public:
char * x;
int y;
A()
{
    cout<<"无参构造"<<endl;
    this->x=new char[0];
    this->y=0;
}

 A(int n)
{
    cout<<"带参构造"<<endl;
    this->y=n;
    this->x=new char[n];
}

A(const A & a)
{
    cout<<"拷贝构造"<<endl;
    this->x=new char[strlen(a.x)+1];
    strcpy(this->x,a.x);
    this->y=a.y;
}

A & operator=(const A & a)
{
    cout<<"重载的赋值运算符"<<endl;
    if(this!=&a)  //判断是否是自赋值
    {
        delete [] this->x;  //释放
        this->x=new char[strlen(a.x)+1];  //创建
        strcpy(this->x,a.x);
        this->y=a.y;
    }
    return  *this;
}
~A()
{
    delete [] x;
    cout<<"析构"<<endl;
}
};
void func01(A aa)
{
}
A func02()
{
A aaa;
return aaa;
}
int main() {
A a(1);
A c = a;
func01(a);
c=func02();
c=a;
return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值