2013-10-21 53 views
2

我正在寫一個簡單的程序來理解新的和刪除操作符重載。 size參數如何傳遞給new運算符?新增和刪除操作符重載

僅供參考,這裏是我的代碼:

#include<iostream> 
#include<stdlib.h> 
#include<malloc.h> 
using namespace std; 

class loc{ 
    private: 
     int longitude,latitude; 
    public: 
     loc(){ 
      longitude = latitude = 0; 
     } 
     loc(int lg,int lt){ 
      longitude -= lg; 
      latitude -= lt; 
     } 
     void show(){ 
      cout << "longitude" << endl; 
      cout << "latitude" << endl; 
     } 
     void* operator new(size_t size); 
     void operator delete(void* p); 
     void* operator new[](size_t size); 
     void operator delete[](void* p); 
}; 

void* loc :: operator new(size_t size){ 
    void* p; 
    cout << "In overloaded new" << endl; 
    p = malloc(size); 
    cout << "size :" << size << endl; 
    if(!p){ 
     bad_alloc ba; 
     throw ba; 
    } 
    return p; 
} 

void loc :: operator delete(void* p){ 
    cout << "In delete operator" << endl; 
    free(p); 
} 

void* loc :: operator new[](size_t size){ 
    void* p; 
    cout << "In overloaded new[]" << endl; 
    p = malloc(size); 
    cout << "size :" << size << endl; 
    if(!p){ 
     bad_alloc ba; 
     throw ba; 
    } 
    return p; 
} 

void loc :: operator delete[](void* p){ 
    cout << "In delete operator - array" << endl; 
    free(p); 
} 

int main(){ 
    loc *p1,*p2; 
    int i; 
    cout << "sizeof(loc)" << sizeof(loc) << endl; 
    try{ 
     p1 = new loc(10,20); 
    } 
    catch (bad_alloc ba){ 
     cout << "Allocation error for p1" << endl; 
     return 1; 
    } 
    try{ 
     p2 = new loc[10]; 
    } 
    catch(bad_alloc ba){ 
     cout << "Allocation error for p2" << endl; 
     return 1; 
    } 
    p1->show(); 
    for(i = 0;i < 10;i++){ 
     p2[i].show(); 
    } 
    delete p1; 
    delete[] p2; 
    return 0; 
} 
+3

我不假設[你先讀這個問題](http://stackoverflow.com/questions/4421706/operator-overloading/4421791#4421791) – WhozCraig

+0

感謝WhozCraig。 – Angus

+1

還要注意:'刪除p2;'應該是'delete [] p2;' –

回答

3

當你寫這樣new loc表達式,編譯器靜態類型信息,讓它知道loc對象有多大。因此,它可以生成將sizeof loc傳遞到loc::operator new的代碼。在創建數組時,編譯器可以通過將數組大小乘以sizeof loc,然後還提供一些額外的空間量(以實現定義的方式確定)來確定需要多少空間來保存陣列中的所有對象,它將在內部用於存儲有關數組中元素數量的信息。

希望這會有所幫助!