c++ 的父类 new 重载, 子类new 对象的时候会调用父类的operater new

子类在new 对象的 时候  父类的new 进行了重载,那么会调用父类的operater new() 函数

#include <iostream>
#include <string>
using namespace std;
class Animal {
    string name;
public:
    void* operator new(size_t size){
        cout<<"operator new print "<<endl;
        Animal *p=(Animal *)malloc(size);
        return p;
    }

};
class Dog: public Animal{
    string age;

};
int main() {
    Dog* al =
    new Dog();
    std::cout << "Hello, World!" << std::endl;
    return 0;
}

输出结果

C:\Users\meto\CLionProjects\untitled6\cmake-build-debug\untitled6.exe
operator new print
Hello, World!

Process finished with exit code 0

在new 子类的时候,必定会调用父类的构造方法,父类的构造方法会new 一个对象,这时候就调用了operater new;

另外你会发现 java 的时候Dog al= new Dog();

                      c++ 的时候Dog * al= new Dog(); 左边是指针类型,右边是对象,并且new 返回的类型也是一个指针类型

 

posted @ 2021-03-25 15:10  张艳涛&java  阅读(210)  评论(0编辑  收藏  举报