NyanHeart 2021-09-30 18:03 采纳率: 66.7%
浏览 40
已结题

char指针输出乱码是怎么回事,应该怎么改?

#include <iostream>
using namespace std;
class Student
{
private:
    char* name;
    int score;
public:
    Student(const char* name, int score)
    {
        this->name = new char(*name);
        this->score = score;
    }
    ~Student()
    {
        if (name != nullptr)
            delete name;
        if (score != NULL)
            score = NULL;
    }
    Student(const Student& a)
    {
        this->name = new char(*a.name);
        this->score = a.score;
    }
    void setName(const char* name)
    {
        this->name = new char(*name);
    }
    void print_info()
    {
        cout << "name:" << this->name << ", " << "score:" << this->score << endl;
    }
};

int main()
{
    Student stu1("Jhon", 98);
    Student stu2(stu1);
    stu2.setName("Tom");
    stu1.print_info();
    stu2.print_info();
    return 0;
}

最后输出,name会显示乱码

img

  • 写回答

1条回答 默认 最新

  • qzjhjxj 2021-09-30 23:24
    关注

    修改如下,供参考:

    #include <iostream>
    #include <string>
    using namespace std;
    class Student
    {
    private:
        char* name;
        int  score;
    public:
        Student(const char* name, int score)
        {
            this->name = new char(strlen(name)+1); //this->name = new char(*name);
            strcpy(this->name,name);
            this->score = score;
        }
        ~Student()
        {
            if (name != NULL)
                delete name;
            if (score != NULL)
                score = NULL;
        }
        Student(const Student& a)
        {
            this->name = new char(strlen(a.name)+1); //this->name = new char(*a.name);
            strcpy(this->name,a.name);
            this->score = a.score;
        }
        void setName(const char* name)
        {
            if(this->name != NULL) delete this->name;
            this->name = new char(strlen(name)+1); //this->name = new char(*name);
            strcpy(this->name,name);
        }
        void print_info()
        {
            cout << "name:" << this->name << ", " << "score:" << this->score << endl;
        }
    };
    int main()
    {
        Student stu1("Jhon", 98);
        Student stu2(stu1);
        stu2.print_info();
    
        stu2.setName("Tom");
        stu1.print_info();
        stu2.print_info();
        
        return 0;
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 10月14日
  • 已采纳回答 10月6日
  • 创建了问题 9月30日

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?