简体   繁体   English

函数C ++中标准库函数的重载

[英]Function Overloading for the standard library functions in C++

I have a free function as part of a class. 我有一个免费的功能作为课程的一部分。 In the constructor for the class i am doing some malloc operations . 在类的构造函数中,我正在做一些malloc操作。 So in the destructor i am trying to free that memory. 所以在destructor我试图释放那个记忆。 But VS10 compiler complains that the 但VS10编译器抱怨说

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, 问候,

You have to use the scope operator to get the correct scope of the free function: 您必须使用范围运算符来获取free函数的正确范围:

::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. ::在开头告诉编译器在全局范围内寻找free函数,而不是在你的类中最近的范围。

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. 这将获取全局命名空间中的free函数,而不是您的类。

#include <cstdio> also puts free and malloc into the std namespace, so std::free and std::malloc will also work. #include <cstdio>也将freemalloc放入std命名空间,因此std::freestd::malloc也可以。

(Use of new / delete should also be considered, as well as smart pointers.) (还应考虑使用new / delete ,以及智能指针。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM