当编译器碰到一个标识符时
它必须能够确定这个标识符所代表的实体的类型和作用域
//: C05:Lookup.cpp
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
// Only produces correct behavior with EDG,
// and Metrowerks using a special option.
#include <iostream>
using std::cout;
using std::endl;
void f(double) { cout << "f(double)" << endl; }
template<class T> class X {
public:
void g() { f(1); }
};
void f(int) { cout << "f(int)" << endl; }
int main() {
X<int>().g();
getchar();
} ///:~
输出
f(int)
在实际的应用系统中存在大量的依赖非标准行为的不规范代码
即使g()中f(1)的调用与其后的f(int)绑定在了一起
编译器的编写者不情愿的改动
//: C05:Lookup2.cpp {-bor}{-g++}{-dmc}
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
// Microsoft: use option -Za (ANSI mode)
#include <algorithm>
#include <iostream>
#include <typeinfo>
using std::cout;
using std::endl;
void g() { cout << "global g()" << endl; }
template<class T> class Y {
public:
void g() {
cout << "Y<" << typeid(T).name() << ">::g()" << endl;
}
void h() {
cout << "Y<" << typeid(T).name() << ">::h()" << endl;
}
typedef int E;
};
typedef double E;
template<class T> void swap(T& t1, T& t2) {
cout << "global swap" << endl;
T temp = t1;
t1 = t2;
t2 = temp;
}
template<class T> class X : public Y<T> {
public:
E f() {
g();
this->h();
T t1 = T(), t2 = T(1);
cout << t1 << endl;
swap(t1, t2);
std::swap(t1, t2);
cout << typeid(E).name() << endl;
return E(t2);
}
};
int main() {
X<int> x;
cout << x.f() << endl;
getchar();
} ///:~
输出
Y<int>::g()
Y<int>::h()
0
global swap
int
1
若名称是关联的
则它的查找是在实例化时进行
非限定的关联名称除外
它是一个普通名称查找
它的查找进行的比较早是在定义时进行