C/C ++中的运算符与函数 [英] Operators vs Functions in C/C++
问题描述
最近有人问我C ++标准运算符(例如new,delete,sizeof)和函数(例如tan,free,malloc)之间的区别.标准"是指默认情况下由编译器套件提供的内容,不是用户定义的.下面是我给出的答案,尽管都没有令人满意的答案.
Someone recently asked me the difference between a C++ standard operator (e.g. new,delete,sizeof) and function (e.g. 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)运算符不需要使用任何标题即可使用:您可以在不包含任何标题的情况下致电new.但是,一个函数(例如free())确实需要强制包含标头.
(1) An operator doesn't need any headers to be included to use it : E.g. you can have a call to new without including any headers. However, a function (say free() ) does need headers included, compulsorily.
(2)在标准头文件中的某个位置定义了一个运算符(即,一个类运算符).功能不是.
(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?
推荐答案
运算符是具有固定语法的 关键字 .那些可以重载的语法可能会有所不同,但这是在界限之内的.即使新的 new
运算符仍然拼写为 new
,并且调用它的语法始终相同.
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.
函数名称是 标识符 ,几乎可以是任意的.没有语法原因,您无法舍弃 malloc()
并使用
bool my_fancy_alloc(void*& memory, unsigned char size, bool zero_it);
相反.(马克:还有 其他原因.就像同事的理智一样.)
instead. (Mark: There are other reasons, though. Like your fellow-workers' sanity.)
这篇关于C/C ++中的运算符与函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!