zoukankan      html  css  js  c++  java
  • Cplus Overolad new and delete Operator

    思考:在C++类中,通过设计类的构造和析构函数,就已经把复杂的内存管理起来了. 及时是简单的结构体,也是有构造和析构函数的,而下面这种情况,可以在非结构中使用.

    /** Operator Overload new and delete */
    
    #include <iostream>
    #include <cstdlib>
    #include <new>
    
    using namespace std;
    
    class MyClass{
    public:
        MyClass(){ x = y = 0; }
        MyClass(int lg, int lt) {
            x = lg;
            y = lt;
        }
        void show(){
            cout << x << " ";
            cout << y << endl;
        }
    
        void *operator new(size_t size);
        void operator delete(void *p);
        void *operator new[](size_t size);
        void operator delete[](void *p);
    
    private:
        int x, y;
    };
    
    /** overloaded new operator */
    void *MyClass::operator new(size_t size){
        void *p;
        cout << "In overloaded new.
    ";
        p = malloc(size);
        if(!p){
            bad_alloc ba;
            throw ba;
        }
        return p;
    }
    
    /** delete operator overloaded */
    void MyClass::operator delete(void *p){
        cout << "In overloaded delete.
    ";
        free(p);
    }
    
    /** new operator overloaded for arrays. */
    void *MyClass::operator new[](size_t size){
        void *p;
        cout << "Using overload new[].
    ";
        p = malloc(size);
        if(!p){
            bad_alloc ba;
            throw ba;
        }
        return p;
    }
    
    /** delete operator overloaded for arrays. */
    void MyClass::operator delete[](void *p)
    {
        cout << "Freeing array using overloaded delete[]
    ";
        free(p);
    }
    
    int main()
    {
        MyClass *objectPointer1, *objectPointer2;
        int i;
    
        try{
            objectPointer1 = new MyClass (10, 20);
        }catch (bad_alloc xa){
            cout << "Allocation error for objectPointer1.
    ";
            return 1;;
        }
    
        try{
            objectPointer2 = new MyClass [10];
        } catch (bad_alloc xa) {
            cout << "Allocation error for objectPointer2.
    ";
            return 1;
        }
    
        objectPointer1->show();
        for( i = 0; i < 10; i++){
            objectPointer2[i].show();
        }
    
        delete objectPointer1;
        delete [] objectPointer2;
    
        return 0;
    }
    

  • 相关阅读:
    web site 和 web application的区别
    Windows Phone开发(10):常用控件(上)
    WPF绑定ListBox
    Cookies的实际存储位置
    parse_str() 函数把查询字符串解析到变量中。
    str_repeat() 函数把字符串重复指定的次数。
    搭建Git本地服务器
    windows下github 出现Permission denied (publickey).解决方法
    ReadSolve 规格严格
    Scp命令(转载) 规格严格
  • 原文地址:https://www.cnblogs.com/zi-xing/p/8459708.html
Copyright © 2011-2022 走看看