c++面向对象构造函数,堆炸了??我定义了三个对象程序却让我输入了四个对象

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstring>
using namespace std;
class student
{
public:
    student();
    char* name;
    char* birthspace;
    int num;
    int age;
    int grades;
    void display();
    student operator+(const class student &c);
    ~student();
};
student student::operator+(const student& c)
{
    student t;
    t.grades = grades + c.grades;
    return t;
}
student::~student()
{
    cout << "\n析构函数\n";
    delete name;
    delete this->name;
    delete    birthspace;
    delete this->birthspace;
}
student::student()
{
    cout << "\n构造函数\n";
    char* name;
    char* birthspace;
    int num;
    int age;
    int grades;
    name = new char;
    this->name = new char;
    birthspace = new char;
    this->birthspace = new char;
    cout << "please enter the name birthplace num age grades:\n" << endl;
    cin >> name
        >> birthspace
        >> num
        >> age
        >> grades;
    strcpy(this->name, name);
    strcpy(this->birthspace, birthspace);
    this->num = num;
    this->age = age;
    this->grades = grades;
    

}
void student::display()
{
    cout << name
        << birthspace
        << num
        << age
        << grades << endl;


}
int main()
{
    student a;
    //在定义对象时会自动调用构造函数
    //所以不用在主函数手动调用构造函数
    student b;
    class student r;
    r = a + b;

    return 0;
}

Microsoft Visual C++ Runtime Library
X
Debug Error!
Program: C:tUsers(i\source\repos\NSEC\Debug\NsEu.exe
HEAP CORRUPTION DETECTED: after Normal block (#236) at
0x00743298.
CRT detected that the application wrote to memory after end of heap
buffer.
(Press Retry to debug the application)

 

student student::operator+(const student& c)
{
     
    student t; //这句会导致要求输入第四个对象
    t.grades = grades + c.grades;
    return t;
}

student::~student()
{
    //崩溃是因为你释放了同一个内存两次,name跟this->name在这里是一个东西
    cout << "\n析构函数\n";
    delete name;
    delete this->name;
    delete    birthspace;
    delete this->birthspace;
}

你这个程序还有很多问题,像构造函数,有大问题,给name分配了一个char的内存,却把它当做字符数组来用,这是不行的。还有就是你还需要自己实现重载复制构造函数和赋值操作符,因为类里面有动态分配的指针,而且你在析构函数里释放内存,如果只是浅拷贝会导致同一个内存被释放多次,得自己实现深拷贝。总之不是对C++很熟的话就别在类里面给指针成员动态分配内存,这涉及内存的管理和C++的三个复制控制函数,轻则内存泄露,重则crash。

你的重载+函数里面不是有个student t?