认识到向上类型转换仅处理地址
如果编译器有一个它知道确切类型的对象,那么在 C++中 对任何函数的调用
将不再使用晚捆绑,或至少编译器不必使用晚捆绑
因为编译器知道对象的确切类型,为了提高效率,当调用这些对象的虚函数
时,很多编译器使用早捆绑
//: C15:Early.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// Early binding & virtual functions
#include <iostream>
#include <string>
using namespace std;
class Pet {
public:
virtual string speak() const { return ""; }
};
class Dog : public Pet {
public:
string speak() const { return "Bark!"; }
};
int main() {
Dog ralph;
Pet* p1 = &ralph;
Pet& p2 = ralph;
Pet p3;
// Late binding for both:
cout << "p1->speak() = " << p1->speak() <<endl;
cout << "p2.speak() = " << p2.speak() << endl;
// Early binding (probably):
cout << "p3.speak() = " << p3.speak() << endl;
getchar();
} ///:~
在p1->speak()和p2.speak()中,使用地址,就意味着信息不完全:p1和p2
可能表示Pet的地址,也可能表示其派生对象的地址,所以必须使用虚函数
输出
p1->speak() = Bark!
p2.speak() = Bark!
p3.speak() =