2015-03-03 71 views
1

我從書上看到一些代碼,就像這樣:爲什麼子類重寫虛函數不能改變父類的默認函數參數?

#include<iostream> 

using namespace std; 

class Father 
{ 
public: 
    virtual void test(int value=520) 
    { 
     cout<<"father:"<<value<<endl; 
    } 
}; 

class Son :public Father 
{ 
public: 
    virtual void test(int value=250) 
    { 
     cout<<"son:"<<value<<endl; 
    } 
}; 

int main() 
{ 
    Son* son =new Son; 
    son->test(); 
    Father* fson= son; 
    fson->test(); 
} 

程序輸出:

son250

son520

書上說,虛擬缺省參數函數在編譯時確定。

我的問題是: 虛擬函數的默認參數爲什麼不在運行時決定?像虛擬功能本身一樣。

回答

3

C和C++的製造商不想讓事情複雜化。實現在編譯時解析的默認參數很簡單,在運行時並不那麼簡單。但是,您可以並應該使用一種解決方法。而不是使用默認參數引入一個更多的沒有參數的虛函數。

class Father 
{ 
public: 
    virtual void test(int value) 
    { 
     cout << "father:" << value << endl; 
    } 


    virtual void test() 
    { 
     test(520); 
    } 
}; 

class Son : public Father 
{ 
public: 
    virtual void test(int value) 
    { 
     cout << "son:" << value << endl; 
    } 

    virtual void test() 
    { 
     test(250); 
    } 
}; 
+0

我覺得現在不需要爲這個功能複雜的語言。 – 2015-03-03 09:08:48

相關問題