我从以下代码中获取了C ++ - Yeswant kanetkar。我是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 :(得分:-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;
}