优化Hoax or what的思考

在抽取MinHeap的时候,涉及到重载,覆盖,虚函数等,有几点之前没注意到的问题在这里总结下:

1. 覆盖(override)只要是函数同名就会被覆盖,子类指针若调用父类的同名不同参数的函数的话,会在编译时期报编译错误;

2. 成员函数在编译时就确定该函数的所属类,同一个类的不同对象共享一份成员函数地址,根据指针的类型调用指定的成员函数,属于early bind;

3. 虚函数采用late bind,就是在运行时才能确定具体调用的函数,根据this指向的内存空间类型,去对应的虚表中取对应的函数,通过同一个slot位置抽象;

4. 成员函数的实现跟全局函数类似,找到该函数对应的逻辑代码段后,将this指针作为参数传入,用于获取分配的内存空间中的数据,包括虚函数地址。

#include<iostream>
using namespace std;

class A {
public:
    void f() {
        cout << "A::f()" << endl;
        g();
        h();
    }
    void g() {
        cout << "A::g()" << endl;
    } 
    virtual void h() {
        cout << "A::h()" << endl;
        g();
    }
};

class B : public A {
public:
    void f() {
        cout << "B::f()" << endl;
        A::f();
    }
    void g() {
        cout << "B::g()" << endl;
    }
    virtual void h() {
        cout << "B::h()" << endl;
        g();
    }
};

int main() {
    B b;
    b.f();
}

上述代码对应的输出结果是:

B::f()
A::f()
A::g()
B::h()
B::g()

 

posted @ 2013-08-26 18:40  litstrong  阅读(150)  评论(0编辑  收藏  举报