首页 > 试题广场 >

对每个可重载的运算符来讲,它既可以重载为友元函数,又可以重载

[单选题]
对每个可重载的运算符来讲,它既可以重载为友元函数,又可以重载为成员函数,还可以重载为非成员函数。
某些运算符必须重载位成员函数,比如  operator new;
某些运算符必须重载为非成员函数,比如  operator >>...
发表于 2017-05-23 10:22:04 回复(0)
operator new 和 operator delete 系列内存分配运算符并非必须重载为成员函数。
援引《C++ Primer (Fifth Devision)》19.1.1节的原文:

Applications can define operator new and operator delete functions in the global scope and/or as member functions. When the compiler sees a new or delete expression, it looks for the corresponding operator function to call. If the object being allocated (deallocated) has class type, the compiler first looks in the scope of the class, including any base classes. If the class has a member operator new or operator delete, that function is used by the new or delete expression. Otherwise, the compiler looks for a matching function in the global scope. If the compiler finds a user-defined version, it uses that function to execute the new or delete expression. Otherwise, the standard library version is used. 

大意如下:
应用程序可以将重载的new/delete定义为全局函数也可以定义为成员函数。当编译器看到一个new/delete表达式,它就开始寻找相应的运算符函数来调用。如果这个被分配内存(或释放内存)的对象是一个class类型,那么编译器首先查找class定义域,包括其基类的定义域。如果在这个class的定义域内找到了一个new/delete成员函数,那么编译器就使用这个函数来执行上文提到的new/delete表达式。假如没有在class定义域内搜索到对应的new/delete成员函数,编译器会在全局作用域内寻找匹配的new/delete函数。如果编译器找到了一个用户自定义的new/delete全局函数,那么编译器就使用这个函数来执行上文提到的new/delete表达式。假如没找到,那么编译器只好使用STL中定义的默认new/delete函数来执行上文提到的new/delete表达式。

编译器对new/delete函数的检索步骤总结如下:
1.class作用域-->找寻自定义实现
2.全局作用域-->找寻自定义实现
3.STL-->找寻默认实现

有个关键点不得不提,即自定义全局new/delete函数掌管全局动态内存分配,可谓一手遮天,所以重载行为必须慎之又慎。
正如Lippman所言:

When we define the global operator new and operator delete functions, we take over responsibility for all dynamic memory allocation. These functions must be correct: They form a vital part of all processing in the program. 


编辑于 2017-08-29 17:54:24 回复(0)
new只能重载为成员函数,输入输出只能重载为非成员函数。
发表于 2017-08-06 15:22:49 回复(0)
注意是每个 对于对象的操作必须为成员函数,比如new
发表于 2018-04-13 12:09:18 回复(0)