Someone recently asked me the difference between a C++ standard operator (eg new,delete,sizeof) and function (eg tan,free, malloc). By "standard" I mean those provided by default by the compiler suite, and not user defined . Below were the answers I gave, though neither seemed satisfactory.
(1) An operator doesn't need any headers to be included to use it : Eg you can have a call to new without including any headers. However, a function (say free() ) does need headers included, compulsorily.
(2) An operator is defined as such (ie as a class operator) somewhere in the standard headers. A function isn't.
Can you critique these answers and give me a better idea of the difference?
Operators are keywords with a fixed syntax. Those which can be overloaded might vary a bit in syntax, but that's within the boundaries. The new
operator is still spelled new
, even when overloaded and the syntax of invoking it is always the same.
Function names are identifiers , which can be almost arbitrary. There's no syntactic reason you couldn't do away with malloc()
and use
bool my_fancy_alloc(void*& memory, unsigned char size, bool zero_it);
instead. (Mark: There are other reasons, though. Like your fellow-workers' sanity.)
(1) isn't strictly true. typeid
is an operator, but its use requires that you include <typeinfo>
.
My answer would simply be that operators are defined as such. ::
doesn't necessarily need to be considered an operator, for instance, but the standard says it is, and so it is.
If you're looking for a more verbose answer, I would go on to mention that operators mostly do not look like functions. And those that do [ sizeof
and typeid
] don't act as functions; their operands are not evaluated at runtime.
An operator is compiled to a sequence of instructions by the compiler.
When the code calls a function , it has to jump to a separate piece of code
运算符具有特殊语法,例如,您可以使用new
(或+
)而不在运算符名称后面的括号中放置参数。
An operator and function are conceptually same. Both of them take some values as input and return some as output. They only difference is there syntax.
我的理解函数名称是goto运算符的表示,在跳转到特定代码位置后,应用程序可以执行一个到多个工作单元,另一方面操作员执行实际的工作单元。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.