zoukankan      html  css  js  c++  java
  • 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:UsersmetoCLionProjectsuntitled6cmake-build-debuguntitled6.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 返回的类型也是一个指针类型

  • 相关阅读:
    附加作业
    个人总结
    wordcount
    vs2013安装及测试
    结对作业电梯调度问题
    阅读下面程序,请回答如下问题:
    补作业:随机生成二元四则运算
    软件工程的认识
    结对编程完结
    结对编程加团队编程
  • 原文地址:https://www.cnblogs.com/zytcomeon/p/14577582.html
Copyright © 2011-2022 走看看