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

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。