vtbl in C++ (virtual function table)
阿新 • • 發佈:2022-05-20
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,類的每個物件有一個額外的指標