首页 > 编程语言 > 详细

careercup-C和C++ 13.3

时间:2014-12-09 22:56:50      阅读:357      评论:0      收藏:0      [点我收藏+]

13.3 C++中的虚函数是如何工作的?

解答

虚函数依赖虚函数表进行工作。如果一个类中,有函数被关键词virtual进行修饰, 那么一个虚函数表就会被构建起来保存这个类中虚函数的地址。同时, 编译器会为这个类添加一个隐藏指针指向虚函数表。如果在派生类中没有重写虚函数, 那么,派生类中虚表存储的是父类虚函数的地址。每当虚函数被调用时, 虚表会决定具体去调用哪个函数。因此,C++中的动态绑定是通过虚函数表机制进行的。

当我们用基类指针指向派生类时,虚表指针vptr指向派生类的虚函数表。 这个机制可以保证派生类中的虚函数被调用到。

class Shape{
public:
    int edge_length;
    virtual int circumference () {
        cout<<"Circumference of Base Classn";
        return 0;
    }
};
class Triangle: public Shape{
public:
    int circumference () {
        cout<<"Circumference of Triangle Classn";
        return 3 * edge_length;
    }
};
int main(){
    Shape *x = new Shape();
    x->circumference(); // prints “Circumference of Base Class”
    Shape *y = new Triangle();
    y->circumference(); // prints “Circumference of Triangle Class”
    return 0;
}

 在上面的代码中,circumference是shape类的虚函数,因此在所有继承shape类的子类里都为虚函数。在C++里,非虚函数的调用时在编译器通过静态绑定确定的,而虚函数的调用则是在运行期通过动态绑定确定的。

careercup-C和C++ 13.3

原文:http://www.cnblogs.com/wuchanming/p/4154347.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!