类中的字符指针数据,必须使用动态分配内存空间吗?还是其它哪里出了问题?

img


这张图中使用了new来创建空间,能够正确的输出Apple

img


这张图没有任何输出结果



#include <iostream>
#include <string>
using namespace std;

class person {
    char* name_;//这个指针只是个指针变量,占用的空间大小也就4个字节
                //如果想存储字符串就必须申请内存,使用name_这个指针指向申请的内存
public:
    person(const char* name)
    {
        name_ = new char[strlen(name) + 1];
        strcpy(name_, name);
        cout << __FUNCTION__ << endl;
    }
    ~person()
    {
        cout << __FUNCTION__ << endl;
        delete[] name_;
        name_ = nullptr;
    }
    void display()
    {
        cout << name_ << " " << endl;
    }
};

class person1 {
    char name_[128];//这是个字符数组,长度为128个字节,可以存储长度为127长度的字符串,字符串需要一个结束符
public:
    person1(const char* name)
    {
        strcpy(name_, name);
        cout << __FUNCTION__ << endl;
    }
    ~person1()
    {
        cout << __FUNCTION__ << endl;
    }
    void display()
    {
        cout << name_ << " " << endl;
    }
};

class person2 {
    string name_;//string帮我们做好了内存申请和释放
public:
    person2(const char* name)
    {
        name_.append(name);
        cout << __FUNCTION__ << endl;
    }
    ~person2()
    {
        cout << __FUNCTION__ << endl;
    }
    void display()
    {
        cout << name_ << " " << endl;
    }
};


int main()
{
    person p("Apple");
    p.display();
    person2 p1("Apple");
    p1.display();
    person2 p2("Apple");
    p2.display();
    return 0;
}

第二个肯定不对啊,类的name指针没有分配空间,进行strcpy就崩溃了
必须像第一个一样分配空间。或者改成 char name[1000],定义成字符数组,就有空间了。