Function Overloading for the standard library functions in C++

戏子无情 提交于 2019-12-23 20:13:18

问题


I have a free function as part of a class. In the constructor for the class i am doing some malloc operations . So in the destructor i am trying to free that memory. But VS10 compiler complains that the

free(pointer); 

doesn't match the signature of the free function of my class.

So question is In a class wherein if we have implemented methods which have same names as that of standard library functions . How to call one over the other.

Regards,


回答1:


You should qualify your call to the function:

void YourClass::free(args) {
  ::free(your_member);
}

This will pick up the free function in the global namespace and not in your class.

#include <cstdio> also puts free and malloc into the std namespace, so std::free and std::malloc will also work.

(Use of new/delete should also be considered, as well as smart pointers.)




回答2:


You have to use the scope operator to get the correct scope of the free function:

::free(pointer);

Having :: at the beginning tells the compiler to look for the free function at the global scope, not the closest scope which is your class.



来源:https://stackoverflow.com/questions/9125692/function-overloading-for-the-standard-library-functions-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!