virtual function c++

 

 

 

以前一直不明白爲何要用虛函數,我只知道這樣的規則, Base b = new derived(); b->do(); 調用的是子類的do();java

virtue class只是一個虛擬的,調用的是子類ide

在不聲明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,屢次重複給不一樣的子類使用對象

相關文章
相關標籤/搜索