Calling an "external" function from a class method
I have a function that I want to call from within a class method. The function is in a file called mergeSort.cpp. Here is a snippet of the .cpp file that the class is implemented in:
// other includes
#include "mergeSort.cpp"
// other methods
void Servers::sortSites() {
mergeSort(server_sites.begin(), server_sites.end(), siteCompare);
}
// remaining methods
When I try to compile I ge开发者_开发技巧t errors saying that mergeSort can't be found. I think this is because it's trying to call Servers::mergeSort. How would I go about calling an external function?
You have to use the "::" external namespace resolutor:
::mergeSort(...);
This tells the compiler to look for the function in the outer namespace. If this particular function is defined in another namespace or class, you have to specify it explicitly:
Namespace::mergeSort(...);
If you don't want to have to resolve the name completely each time you use it, you can import the name into the current namespace by either using:
using namespace Namespace;
or
using Namespace::mergeSort;
(where Namespace
is the name in which mergeShort()
is defined).
There seem to be a couple of issues here. Firstly, does Servers::mergeSort
actually exist? You've speculated that it's looking for that, but you haven't actually said that there is such a thing. If there isn't, that's not the problem. In that case, a likely reason it can't see mergeSort would be that it's not in the global namespace (as other answers have speculated). If Servers::mergeSort
does exist, then see Diego's answer.
A separate issue is -- are you including the .cpp file (which is generally a bit odd) because mergeSort is a template? If no, you should probably be including the accompanying .h I guess. If yes, a more usual pattern is to include the file with the template code in the header, like so:
// mergeSort.h
// <Begin include guard
// <Lots of header stuff>
#include "mergeSort.tpp"
// <End include guard>
Then you include mergeSort.h elsewhere, and it's one thing less for clients to remember.
Check if mergeSort()
is in a particular namespace.
精彩评论