vtbl in C++ (virtual function table)
class Container
{
public:
virtual double& operator[](int) = 0; virtual int size() const = 0;
virtual ̃Container() {}
// pure virtual function
// const member function (§3.2.1.1) // destructor (§3.2.1.2)
};
void use(Container& c)
{
const int sz = c.size();
for (int i=0; i!=sz; ++i) cout << c[i] << '\n';
}
class Vector_container : public Container
{ // Vector_container implements Container Vector v;
public:
Vector_container(int s) : v(s) { } // Vector of s elements ̃Vector_container() {}
double& operator[](int i) { return v[i]; }
int size() const { return v.size(); } };
class List_container : public Container { // List_container implements Container std::list<double> ld; // (standard-library) list of doubles (§4.4.2)
public:
List_container() { } // empty List List_container(initializer_list<double> il) : ld{il} { } ̃List_container() {}
double& operator[](int i);
int size() const { return ld.size(); }
};
double& List_container::operator[](int i) {
for (auto& x : ld) {
if (i==0) return x;
−−i; }
throw out_of_range("List container"); }
void h() {
List_container lc = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
use(lc); }
void g() {
Vector_container vc {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
use(vc); }
g()和h()中的use调用给Container &c绑定了不同的对象,他们分别动态绑定到Vector_container和List_container的operator[]成员上
因此,Container对象必包含runtime选择正确函数的信息
编译器将虚函数的名字转换成函数指针表中对应的索引值,这个表称为虚函数表.
空间开销:每个类有一个vtbl,类的每个对象有一个额外的指针
本文来自博客园,作者:ijpq,转载请注明原文链接:https://www.cnblogs.com/ijpq/p/16291824.html