Qf要变强!!O_o 2022-03-30 13:37 采纳率: 66.7%
浏览 35
已结题

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

img


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

img


这张图没有任何输出结果

  • 写回答

2条回答 默认 最新

  • stone_wangzx 2022-03-30 14:12
    关注
    
    
    #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;
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 4月7日
  • 已采纳回答 3月30日
  • 创建了问题 3月30日