第六周 项目一-深复制体验(2)(3)

来源:互联网 发布:c语言字符串的定义 编辑:程序博客网 时间:2024/06/06 04:32

问题

 

(2)将注释(a)所在的那一行去掉,会出现什么现象?为什么?为什么a数据成员所占用的存储空间要在aa长度基础上加1?若指针a不是指向字符(即不作为字符串的地址),是否有必要加1?

提示错误,因为没有为a指针初始化地址,a将变为野指针。

字符串结束时需要用'\0'。

没有必要。
(3)为类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];        strcpy(a, aa);    }    ~A()    {        delete []a;    }    A (A &c)    {        a = new char[strlen(c.a)+1];        strcpy(a, c.a);    }    void output()    {        cout<<a<<endl;    }};int main(){    A a("good morning, code monkeys!");    a.output();    A b(a);    b.output();    return 0;}


运行结果:

知识点总结:

复制构造函数

学习心得:

好好学习 天天向上

1 0