我在类Base中使用了这个操作符重载:
void* operator new(std::size_t sz1) {
//Se llama a la funcion de xMemoryManager
// std::printf("global op new called, size = %zu\n",sz);
cout<<"operador new"<<endl;}
但是我从基类继承到派生类,并且我在派生类中有以下代码:
xPointer<Pruebas> *xPruebas;
xPruebas=new xPointer<Pruebas>;
xPointer<Pruebas> *xPruebas1;
xPruebas1=new xPointer<Pruebas>;在这几行中,我需要使用基本操作符new,而不是Base类的重载操作符。
我怎么能做到这一点?
发布于 2016-04-10 09:25:32
为派生类编写operator new,并在其中调用::operator new。
发布于 2016-04-10 09:46:04
您需要在派生类中重写operator new函数。这里有两个我能想到的策略。下面的程序展示了如何使用它们。
#include <iostream>
#include <cstdint>
#include <cstdlib>
#include <new>
struct Base
{
void* operator new(std::size_t sz)
{
return malloc(sz);
}
};
struct Derived1 : Base
{
// Simple override.
void* operator new(std::size_t sz)
{
return ::operator new(sz);
}
};
struct Derived2 : Base
{
// Can be used as placement new.
void* operator new(std::size_t sz, void* p)
{
return p;
}
};
int main()
{
// Use operator new in the basic form.
Derived1* ptr1 = new Derived1;
std::cout << ptr1 << std::endl;
// Use operator new in the placement new form.
// Allocate memory for the object first using global operator new.
// Then call the placement new.
void* p = ::operator new(sizeof(Derived2));
Derived2* ptr2 = new (p) Derived2;
std::cout << ptr2 << std::endl;
}https://stackoverflow.com/questions/36524669
复制相似问题