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

  • 相关阅读:
    java获取服务器的ip和地址
    如何产生好的词向量
    谈谈评价指标中的宏平均和微平均
    在NLP中深度学习模型何时需要树形结构?
    Windows下MetaMap工具安装
    ML 感知机(Perceptrons)
    ML 神经网络 NeuralNetworks
    NLP-特征选择
    ML 逻辑回归 Logistic Regression
    ML 线性回归Linear Regression
  • 原文地址:https://www.cnblogs.com/wuchanming/p/4154347.html
Copyright © 2011-2022 走看看