第6周项目1-深复制体验(3)

时间:2022-09-15 00:22:48

问题描述:

  为类A增加复制构造函数,用下面的main函数测试

int main()
{
    A a("good morning, code monkeys!");
    a.output();
    A b(a);
    b.output();
    return 0;
}

代码:

#include<iostream>
#include<cstring>
using namespace std;
class A
{
private:
    char *a;
public:
    A(char *aa)
    {
        a = new char[strlen(aa)+1];  //(a)这样处理的意义在于:______________________________
        strcpy(a, aa);  //(b)数据成员a与形式参数aa的关系:___________________________________
    }
    A(A &aa)
    {
        this->a=new char[strlen(aa.a)+1];
        strcpy(this->a,aa.a);
    }
    ~A()
    {
        delete []a;   //(c)这样处理的意义在于:  ___________________________________________
    }
    void output()
    {
        cout<<a<<endl;
    }
};
int main(){
    A a("good morning, code monkeys!");
    a.output();
    A b(a);
    b.output();
    return 0;
}


 

运行结果:

第6周项目1-深复制体验(3)