[英]overriding functions in c++
#include <iostream>
using namespace std;
class Base {
public:
virtual void some_func(int f1)
{
cout <<"Base is called: value is : " << f1 <<endl;
}
};
class Derived : public Base {
public:
virtual void some_func(float f1)
{
cout <<"Derived is called : value is : " << f1 <<endl;
}
};
int main()
{
int g =12;
float f1 = 23.5F;
Base *b2 = new Derived();
b2->some_func(g);
b2->some_func(f1);
return 0;
}
輸出為:
Base is called: value is : 12
Base is called: value is : 23
為什么第二個調用b2->some_func(f1)
調用Base
類的函數,即使Derived
類中有可用float作為參數的版本?
Base
的指針僅知道int
方法,因此它將執行縮小轉換(應該有一個警告)並調用Base::some_func(int)
。 您已經將重載與覆蓋混淆了,對於覆蓋,函數的簽名必須保持不變。 請再次檢查c ++文檔。.希望這對您有所幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.