对于"+"运算符重载,这很容易理解。 c = c1.operator+(c2)是函数符号,c = c1 + c2是运算符符号。
但是,我只是不明白new运算符的重载。在下面的代码中:
请告诉我在处理student * p = new student("Yash", 24);时发生了什么,为什么调用void * operator new(size_t size)。以及为什么在输入28时大小为operator new(size_t size)

// 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构造函数的参数,它们不会传递给operator new,后者仅负责为student对象分配足够的内存。
为了为student对象分配足够的内存,必须告知operator 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;
}
实际上是不正确的,因为您创建的不是studentoperator new对象。但是,使用malloc的注释掉的代码是正确的。
要查看此问题,您应该添加以下内容
student(string name, int age)
{
    cout<< "Constructor is called with " << name << " and " << age "\n" ;
    this->name = name;
    this->age = age;
}
现在,您将看到错误的版本为一个对象调用了两个构造函数。这是因为您错误地从operator new调用了构造函数。
可以将任意值从用户代码显式传递给operator new。如果要对此进行调查,请查找新的展示位置。

关于c++ - 如何理解新的运算符(operator)重载?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/62727464/

10-11 18:26