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,多次重复给不同的子类使用

原文地址:https://www.cnblogs.com/kyxyes/p/3995933.html