函数名字查找步骤如下:
1:在使用该函数的函数的作用域中查找。
2:在函数参数所在的名字空间中查找。
如下的一段代码:
#include <stdio.h>
#include <string>
using namespace std;
namespace SNSTest
{
struct SSTTest
{
int na;
};
int fun(const SSTTest& STTest)
{
return printf("SNSTest na = %d/n",STTest.na);
}
}
void testfun(const SNSTest::SSTTest& STTest,int ni)
{
fun(STTest);
}
int main()
{
SNSTest::SSTTest STTest;
STTest.na = 2;
testfun(STTest,1);
return 0;
}
编译器对于fun首先会在testfun所在的文件进行查找,结果没有找到,发现fun的参数来自名字空间SNSTest
于是到名字空间SNSTest中查找,这次顺利找到。这里有这么几个问题需要考虑:
1:规则1和规则2之间存在优先级关系么?
2:一个函数可能有多个参数,参数之间是否存在查找的优先级别?
下面通过实验来解决上面的问题:
#include <stdio.h>
#include <string>
using namespace std;
namespace SNSTest
{
struct SSTTest
{
int na;
};
int fun(const SSTTest& STTest)
{
return printf("SNSTest na = %d/n",STTest.na);
}
}
int fun(const SNSTest::SSTTest& STTest)
{
return printf("na = %d/n",STTest.na);
}
void testfun(const SNSTest::SSTTest& STTest,int ni)
{
fun(STTest);
}
int main()
{
SNSTest::SSTTest STTest;
STTest.na = 2;
testfun(STTest,1);
return 0;
}
在testfun的作用域中定义了一个函数fun,如果规则1和规则2之间存在优先级,那么肯定是可以编译通过的,但vs2005编译的时候提示如下错误:
error C2668: 'fun' : ambiguous call to overloaded function
f:/app/test/test/test.cpp(19): could be 'int fun(const SNSTest::SSTTest &)'
f:/app/test/test/test.cpp(13): or 'int SNSTest::fun(const SNSTest::SSTTest &)' [found using argument-dependent lookup]
while trying to match the argument list '(const SNSTest::SSTTest)'
显然是找到了多个的fun,而且重载解析无法判断出哪个更优。这就证明规则1和规则2之间不存在优先级关系。