2015-01-05 52 views
-2

下面的代碼讓我們從C++ - Yeswant kanetkar。我是CPP新手,在重載新操作員時出現以下錯誤。CPP運算錯誤超載新運算符

error: invalid conversion from 'char' to 'void*' [-fpermissive]| 
error: initializing argument 2 of 'void* operator new [](std::size_t, void*)' [-fpermissive]| 
error: invalid conversion from 'char' to 'void*' [-fpermissive]| 
error: initializing argument 2 of 'void* operator new [](std::size_t, void*)' [-fpermissive]| 

的程序如下:

#include <iostream> 
#include <stdlib.h> 
#include <new> 
#include<stdio.h> 
#include<string.h> 
using namespace std; 

int main() 
{ 
    void memwarning(); 
    void *operator new(size_t,int); 
    void operator delete(void *); 

    char *p = new('$') char[100]; 
    cout<<endl<<"First Allocation : p = "<<hex<<long(p)<<endl; 
    for(int i = 0; i < 100; i++) 
    cout << p[i]; 

    delete p; 

    p = new('*')char[64000u]; 
    delete p; 

    return 0; 
} 

void memwarning() 
{ 
    cout <<endl<<"Free Store has now gone empty"; 
    exit(1); 
} 

void * operator new(size_t sz, int setvalue) 
{ 
    void *p; 

    p = malloc(sz); 
     if(p==NULL) 
    memwarning(); 

    memset(p,setvalue,sz); 
    return (p); 
} 

void operator delete(void *pp) 
{ 
    free(pp); 
} 

,這是什麼錯誤的原因是什麼?

+0

'這個錯誤的原因是什麼?'因爲 - 'Yeswant kanetkar'的書是非標準的。 – Sadique

+0

你可以解決這個問題,並建議我一些好書 –

+0

轉到[常見問題](http://stackoverflow.com/questions/tagged/c%20or%20c%2b%2b?sort=frequent&pageSize=15) – Sadique

回答

-1

當你分配一個數組時,你正在調用new [],當你刪除一個數組時,你應該使用delete []。這些是不同於new和delete的操作符。解決這個問題會導致編譯錯誤:

int main() 
{ 
    void memwarning(); 
    void *operator new(size_t,int); 
    void operator delete(void *); 
    char *p = new('$') char; 
    cout<<endl<<"First Allocation : p = "<<hex<<long(p)<<endl; 
    for(int i = 0; i < 1; i++) 
     cout << p[i]; 

    delete p; 

    p = new('*')char; 
    delete p; 

    return 0; 
}