簡體   English   中英

C ++中的重寫函數

[英]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作為參數的版本?

  1. 實際上,它沒有被覆蓋,因為它的參數沒有相同的類型。
  2. 由於未被覆蓋,因此指向Base的指針僅知道int方法,因此它將執行縮小轉換(應該有一個警告)並調用Base::some_func(int)

您已經將重載與覆蓋混淆了,對於覆蓋,函數的簽名必須保持不變。 請再次檢查c ++文檔。.希望這對您有所幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM