请使用delete的重载来实现
时间: 2024-04-11 22:29:04 浏览: 81
17~C++ new和delete运算符重载
当一个A类型数据被删除时,我们可以重载A类中的`operator delete`函数,以输出"del A"的消息,并调用默认的`operator delete`函数来释放内存。同样,当一个B类型数据被删除时,我们可以重载B类中的`operator delete`函数,以输出"del B"的消息,并调用默认的`operator delete`函数来释放内存。
以下是对类A和类B进行重载的示例代码:
```cpp
#include <iostream>
using namespace std;
class A {
public:
void* operator new(size_t size) {
void* p = ::operator new(size);
cout << "new A" << endl;
return p;
}
void operator delete(void* p) {
cout << "del A" << endl;
::operator delete(p);
}
};
class B : public A {
public:
void* operator new(size_t size) {
void* p = ::operator new(size);
cout << "new B" << endl;
return p;
}
void operator delete(void* p) {
cout << "del B" << endl;
::operator delete(p);
}
};
A* dataArray[1001];
int len = 0;
int main() {
dataArray[++len] = new A;
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
delete dataArray[i];
if (typeid(*dataArray[i]) == typeid(A)) {
dataArray[++len] = new B;
} else {
dataArray[++len] = new A;
}
}
return 0;
}
```
这段代码中,我们重载了A类和B类的`operator new`和`operator delete`函数,以实现在分配和释放内存时输出相应的消息。在主函数中,我们使用delete关键字删除dataArray数组中的对象,并根据需要创建新的A或B对象。
阅读全文