[英]Overloaded function in derived class with Polymorphism (C++)
考慮這個代碼示例:
#include <iostream>
using namespace std;
class Base
{
private:
int number;
public:
Base():number(10){}
~Base(){}
virtual void print()
{
cout << "Base class" << endl;
}
};
class Derived : public Base
{
public:
Derived():Base(){}
~Derived(){}
void print(int value)
{
//printing number in Base class and paramter value
cout << "Derived with value " << value << " number is" << number << endl;
}
};
我想使用多態並調用重載的print()
函數。
所以使用這些類如下:
void somewhere_else()
{
Base* polymorphism = new Derived();
polymorphism->print(5); //Error indicating there are too many parameter
//thinking that I am trying to use print in Base class
((Derived*)polymorphism)->print(5)
//This works as I am casting the variable as Derived variable
}
不幸的是,我無法從基類指針調用 print()(編譯錯誤,請參閱上面的注釋)。 我只能用演員表來稱呼它。 有沒有更好的方法來保持多態性並且仍然基於派生類調用重載函數?
在您的代碼中,您有兩個不同的成員函數,它們具有不同的簽名:
print()
。 它在Base
聲明和定義,並在Derived
繼承int
參數的非虛擬print()
。 它僅針對Derived
聲明和定義所以基礎對象不知道帶有 int 參數的打印函數。 這就是為什么你需要施放(順便說一句,如果你需要的話,這是一種應該敲響警鍾的症狀)。
怎么提高 ?
首先,如果要覆蓋派生類中的虛函數,請使用關鍵字override
:
class Derived : public Base
{
public:
Derived():Base(){}
~Derived(){}
void print(int value) override
{
...
}
};
這將確保在函數簽名中出現細微不匹配時出現錯誤消息:
prog.cpp:23:10: error: ‘void Derived::print(int)’ marked ‘override’, but does not override
void print(int value) override
^~~~~
然后確保簽名在基類和派生類中對齊(即兩者都采用 int 參數或不采用它們。
請注意,您不能在派生類中訪問基類的private
成員。 您必須將number
定義為protected
才能在Derived
打印它。
最后,如果您有一個具有虛擬成員的基類,那么系統地使析構函數成為虛擬成員是一個合理的做法。 這將避免更復雜的類的細微錯誤:
class Base
{
protected:
int number;
public:
Base():number(10){}
virtual ~Base(){}
virtual void print(int value)
{
...
}
};
這里是在線演示
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.