我为包含整数变量和字符指针的类重载了new运算符。当重载时,new运算符仅为整数分配内存,因为它首先创建内存然后调用构造函数。有人可以告诉我如何纠正这个问题吗?
//program for overloading new operator
//header files
#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
class Student
{
char *name;
int age;
public:
Student(char *name,int age)
{
strcpy(name,this->name);
this->age=age;
}
void disp()
{
cout<<"\n name is "<<name<<" age is "<<age<<endl;
}
void * operator new(size_t s)
{
cout<<" \n in new block and size is "<< s;
void *ptr=malloc(s);
if(!ptr) cout<<"\n memory full ";
else return ptr;
}
void operator delete(void *ptr)
{
cout<<" \n in delete block ";
free(ptr);
}
};
main()
{
clrscr();
Student *ob=new Student("abc",15);
ob->disp();
delete ob;
getch();
}
产生输出
在新区块中,大小为4 名字是年龄是15
删除块中的
答案 0 :(得分:1)
来自operator new, operator new[]
特定于类的重载
单对象和数组分配函数都可以定义为类的公共静态成员函数(版本(15-18))。如果已定义,则这些分配函数由new-expressions 调用,以便为单个对象和此类的数组分配内存,
为了完整起见,如果必须使用char *,则可以使用strlen,new,strncpy和delete来执行此操作。 请勿使用strcpy,因为这会导致溢出。。 (要在VS2015中进行以下编译,您需要将 _CRT_SECURE_NO_WARNINGS添加到预处理器定义中。)
int length = strlen(source) + 1;
char *destination = new char[length];
if (destination) {
strncpy(destination, source,length);
}
...
delete destination //do not forget to free the allocate memory
这是学生班。
#include <iostream>
#include <string>
// class-specific allocation functions
class Student {
char *nameCharArray; //this only for demonstration
std::string name; //prefer string
int age;
public:
Student(char *name, int age) : age(age)
{
int length = strlen(name) + 1;
nameCharArray = new char[length];
if (this->nameCharArray) {
strncpy(this->nameCharArray, name, length);
}
this->name = std::string(nameCharArray);
}
Student(std::string &name, int age) : name(name), age(age) {}
~Student() {
std::cout << "Freeing name... " << std::endl;
delete nameCharArray;
}
std::string getName() const {
return name;
}
static void* operator new(std::size_t sz)
{
std::cout << "custom new for size " << sz << '\n';
return ::operator new(sz);
}
static void operator delete(void* ptr, std::size_t sz)
{
std::cout << "custom delete for size " << sz << '\n';
::operator delete(ptr);
}
};
这是代码的使用方式
int main() {
char name[] = "studentname";
Student* p1 = new Student(name, 12);
std::cout << p1->getName() << std::endl;
delete p1;
}