gpt4 book ai didi

c++ - 为类重载运算符 new

转载 作者:IT老高 更新时间:2023-10-28 21:50:46 25 4
gpt4 key购买 nike

当我们重载类的 new 操作符时,我们将函数声明为成员函数。例如:

class OpNew {
public:
OpNew() { cout << "OpNew::OpNew()" << endl;}
void* operator new(size_t sz) {
cout << "OpNew::new: "
<< sz << " bytes" << endl;
return ::new char[sz];
}
};

语句 OpNew *obj = new OpNew 如何在幕后工作?因为重载的 new 是 OpNew 类的成员,而不是静态的。那么编译器如何确保对 new 成员函数的调用成功呢?

最佳答案

An operator new() or operator new[]() for a class is always a static class member, even if it is not declared with the keyword static.

C++ 标准的内容(草案 n3242),在 [class.free] 部分:

Any allocation function for a class T is a static member (even if not explicitly declared static).

关于c++ - 为类重载运算符 new,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5406199/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com