zoukankan      html  css  js  c++  java
  • virtual function c++

    之前一直不明白为什么要用虚函数,我只知道这样的规则, Base b = new derived(); b->do(); 调用的是子类的do();

    virtue class只是一个虚拟的,调用的是子类

    在不声明virtue的时候,b->do()调用的是指针所属的类的do(),而不是所指向子类的do()

    看了下面这个例子恍然大悟理解virtue的奥秘 http://stackoverflow.com/questions/429125/override-and-overload-in-c

    truct base {
        virtual void print() { cout << "base!"; }
    }
    
    struct derived: base {
        virtual void print() { cout << "derived!"; }
    }
    Now, if you have an object and call the print member function, the print function of the derived is always called, because it overrides the one of the base. If the function print wasn't virtual, then the function in the derived wouldn't override the base function, but would merely hide it. Overriding can be useful if you have a function that accepts a base class, and every one that's derived from it:
    
    void doit(base &b) {
        // and sometimes, we want to print it
        b.print();
    }
    

      可以看出在doit里面,你可以传任何对象,只要是属于base的子类 这样1,你不用声明具体的类 2,多次重复给不同的子类使用

  • 相关阅读:
    Java中的Java.lang.ThreadLocal类
    Java中线程的生命周期和状态
    Circular Linked List数据结构
    Linked List数据结构
    JVM如何工作
    JVM运行时数据区域
    queue数据结构
    stack数据结构
    Java中Set/HashSet的内部处理
    POJO,JavaBean 以及他们之间的区别
  • 原文地址:https://www.cnblogs.com/kyxyes/p/3995933.html
Copyright © 2011-2022 走看看