对于“+”
运算符重载,它非常容易理解。 C=c1.运算符+(c2)
是函数表示法,C=c1+c2
是运算符表示法。
但是,我无法理解New
运算符重载。 在以下代码中:
请告诉我处理student*p=new student(“yash”,24)时发生了什么;
为什么调用void*operatornew(size_t size)
。 以及输入operator new(size_t size)
时大小为28
的原因。
// 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;
}
中的参数
student * p = new student("Yash", 24);
是student
构造函数的参数,它们不会传递给运算符new
,后者的唯一职责是为student
对象分配足够的内存。
为了给student
对象分配足够的内存,必须告诉运算符new
需要分配多少内存,这就是28
,它是sizeof(student)
的值。
所以您代码
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;
}
实际上是不正确的,因为您正在创建一个student
对象,而该对象不是operatornew
的责任。 但是,使用malloc
的注释掉的代码是正确的。
要查看此问题,应添加以下内容
student(string name, int age)
{
cout<< "Constructor is called with " << name << " and " << age "\n" ;
this->name = name;
this->age = age;
}
现在您将看到您的bug版本为一个对象调用了两个构造函数。 这是因为您错误地从operatornew
调用了构造函数。
可以将用户代码中的任意值显式传递给运算符new
。 如果你想调查这个,然后查找新的位置。