我已经为包含整数变量和字符指针的类重载了 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();
}
产生输出
在新 block 中,大小为 4 名字是15岁
在删除 block 中
最佳答案
来自 operator new, operator new[]
Class-specific overloads
Both single-object and array allocation functions may be defined as public static member functions of a class (versions (15-18)). If defined, these allocation functions are called by new-expressions to allocate memory for single objects and arrays of this class,
- 因此 new 运算符为类的新实例分配内存,而不是为类的属性分配内存。
- 如果您需要为类的属性分配内存,例如在构造函数中。
- 避免将 char* 用于字符串。而是使用 C++ Strings .
- 尽可能避免使用指针。看看smart pointers .
为了完整起见,如果必须使用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
这是学生类。
- 第一个构造函数接受一个 char*(仅用于演示目的!)
- 但更好的是,第二个构造函数使用
- 没有指针,
- 它使用 C++ 字符串,并且
- 使用构造函数初始化列表来设置属性。
- new 运算符(仅委托(delegate)给全局 new 运算符)。
- delete operator (为了完整起见,委托(delegate)给全局删除运算符(operator))。
.
#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;
}
关于c++ - 重载新运算符时,它不会为 char 指针分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39398022/