本文介绍了为类重载运算符new的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我们重载一个类的新运算符时,我们将该函数声明为一个成员函数。
例如:
When we overload new operator of a class, we declare the function as a member function.For eg:
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
在发动机罩下工作?因为重载的新是OpNew类的成员而不是静态的。那么编译器如何保证这个调用 new
成功函数成功?
How does the statement OpNew *obj = new OpNew
work under the hood ? as overloaded new is a member of OpNew class not a static. So how does compiler ensure this call to new
member function succeeds?
推荐答案
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.
这篇关于为类重载运算符new的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!