美文网首页
十二、重载new、delete、()

十二、重载new、delete、()

作者: 木鱼_cc | 来源:发表于2018-06-07 15:23 被阅读0次

    1.堆内存操作符(operator new/delete)

    适用于极个别情况需要定制的时候才用的到。一定很少用。

    //重载的new delete,虽然说是用malloc和free实现,但还是会调用类的构造函数
    class A{
    public:
          A(){
           this->a = 0;
           cout<<"调用了无参构造函数"<<endl;
         }
         A(int a){
           cout<<"调用了有参A(int a)构造函数"<<endl;
           this->a = a;
         }
        ~A(){
            cout<<"调用了析构函数"<<endl;
         }
    
        //不能写在全局,不然全部都被改变了!
        void * operator new(size_t size){
            cout<<"重载new操作符"<<endl;
            return malloc(size);
        }
    
       void * operator new[](size_t size){
            cout<<"重载 new[] 操作符"<<endl;
            return malloc(size);
        }
    
       
        void operator delete(void* p){
              cout<<"重载了delete操作符"<<endl;
              if(p!=NULL)free(p);
      }
    
       void operator delete[](void* p){
              cout<<"重载了delete[]操作符"<<endl;
              if(p!=NULL)free(p);
      }
    
    private:
        int a;
    }
    
    
    int main(void){
       
       A *ap = new A;//调用我们的重载new
       delete ap;
    
      int *array_p = new int[10];//开辟一个数组new[]
      delete[] array_p;
    
    
      A *array_p = new A[10];//开辟了10个A对象。数组首地址array_ap
      delete[] array_p;
    
    
       return 0;
    }
    
    

    2.函数调用符号 (operator () )

    把类对象像函数名一样使用。
    仿函数(functor),就是使一个类的使用看上去象一个函数。其实现就是类中实现一个operator(),这个类就有了类似函数的行为,就是一个仿函数类了。

    class 类名{
       返值类型 operator()(参数类型)函数体
    }
    
    
    #include <iostream>
    using namespace std;
    
    class Sqr
    {
    public:
        int operator()(int i){
            return i*i;
         }
        double operator()(double d){
            return d*d;
         }
    };
    
    //STL C++的标准模板库经常使用
    
    //a 普通int
    //fp-->int(*)(int)
    void func(int a,int(*fp)(int)
    {
        cout<<a<<"的平方结果是"<<endl;
        cout<<fp(a)<<endl;
    }
    
    int s_sqr(int a)
    {
       return a*a;
    }
    
    int main()
    {
      Sqr sqr;
      
       //sqr对象当成一个函数来使用
       //这种写法,就是仿函数,将sqr对象编程一个函数来使用,编译器认为s是一个函数。
       int i = sqr(4);//sqr.operator()(4);
       double d = sqr(5.5);
       cout<<i<<endl;
       cout<<d<<endl;
    
       int b = 20;
       func(b,s_sqr);//通过func调用一个s_sqr回调函数
    
    
       return 0;
    }
    

    相关文章

      网友评论

          本文标题:十二、重载new、delete、()

          本文链接:https://www.haomeiwen.com/subject/cfsgsftx.html