任何人都可以解释以下程序中发生的情况
// CPP program to demonstrate
// Overloading new and delete operator
// for a specific class
#include<iostream>
#include<stdlib.h>
using namespace std;
class student
{
string name;
int age;
public:
student()
{
cout<< "Constructor is called\n" ;
}
student(string name, int age)
{
this->name = name;
this->age = age;
}
void display()
{
cout<< "Name:" << name << endl;
cout<< "Age:" << age << endl;
}
void * operator new(size_t size)
{
cout<< "Overloading new operator with size: " << size << endl;
void * p = ::new student();
//void * p = malloc(size); will also work fine
return p;
}
void operator delete(void * p)
{
cout<< "Overloading delete operator " << endl;
free(p);
}
};
int main()
{
student * p = new student("Yash", 24);
p->display();
delete p;
}
重载new运算符有什么用,在我对上述程序的理解中,重载的new运算符仍在使用malloc分配内存,而无需重载new运算符就可以了吗?
如果我错了,请纠正我。
谢谢!