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

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

修改如下,供参考:

#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;
}