2009-08-24 25 views

回答

10

不,這不是他們的確切目的。虛擬功能是以面向對象的語言實現type polymorphism的手段。

2

是的,這是確切的目的

1

實現多態性。

2

現在,您可以擁有對基類對象的引用的集合,並將派生類對象的引用放在那裏,通過任何引用調用虛函數而不必知道實際的派生類,並且每次都調用派生類最多的覆蓋函數。這就是所謂的多態。

2

需要的是派生類可以重寫,它的行爲與您的預期相同。

反過來創造當派生類的方法,指定新的關鍵字 - 在這種情況相匹配的變量的類型,使用該函數的版本,因此:

derived foo = new derived(); 
base foo2 = foo; 

foo2.bar(); // If bar() is virtual, and overriden in derived, it will use that implementation. 
foo.bar(); // if bar() is not virtual, this may be calling a completely different function, if derived defines a new version