我想在C++中嘗試運行時多態。有人能解釋我這個程序的輸出嗎?我運行它,它給了我一個Derived的輸出(意味着派生類的函數f()被調用)。另外,如果我取消註釋語句 - 程序的預期行爲是什麼 - d.f(); ?C++運行時多態 - 關於默認參數
// Example program
#include <iostream>
#include <string>
class Base {
public :virtual void f(int a = 7){std::cout << "Base" <<std::endl;}
};
class Derived : public Base {
public :virtual void f(int a) {std::cout << "Derived" <<std::endl;}
};
int main() {
Derived d;
Base& b = d;
b.f();
//d.f();
return 0;
}
如果你想確保你的'Derived :: f()'在你的'Base :: f()'上按照預期工作,你可以在函數聲明之前使用關鍵詞'override',例如: 'virtual void f(int a)override {std :: cout <<「Derived」<< std :: endl; }'這將確保預期派生函數的正確函數將被調用,以給你實現你想要的。 –