为类重载运算符new

编程入门 行业动态 更新时间:2024-10-18 14:20:55
本文介绍了为类重载运算符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?

推荐答案

运算符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.

类 T 的任何分配函数都是静态成员(即使没有显式声明 static )。 / p>

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

更多推荐

为类重载运算符new

本文发布于:2023-06-03 12:20:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/473802.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:运算符

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!