• careercup-C和C++ 13.3


    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++里,非虚函数的调用时在编译器通过静态绑定确定的,而虚函数的调用则是在运行期通过动态绑定确定的。

  • 相关阅读:
    二、JVM — 垃圾回收
    一、JVM — Java内存区域
    四、JVM — 类文件结构
    java 如何重写equal 和hashcode方法(最佳实践)
    Java关于继承中的内存分配
    Linux — 基础知识
    Zookeeper — 应用场景
    分布式服务接口请求的顺序性如何保证?
    如何设计一个高并发系统?
    索引策略
  • 原文地址:https://www.cnblogs.com/wuchanming/p/4154347.html
Copyright © 2020-2023  润新知