[英]Binary operator overloading and polymorpism
我正在嘗試制作一個運算符,允許我將 integer 添加到我的一個班級,但我遇到了如下問題。
struct Base
{
//Will have value of zero
};
struct Derived : public Base
{
int value_;
};
int & operator+=(int & num, Base & b);
int & operator+=(int & num, Derived & d);
隨着運營商實施
int & operator+=(int & num, Base & b)
{
return num;
}
int & operator+=(int & num, Derived & d)
{
num += d.value_;
return num;
}
所以我有一個向量,我試圖遍歷它並將所有值添加到一個 integer。但是,即使是 Derived 類型的值也不會更改總和。
如何使運算符重載多態?
這是一個很好的博士。 dobbs 文章為您的問題提供了 3 種解決方案http://drdobbs.com/cpp/200001978其中之一,我在想同樣的事情,就是您可以依賴於虛擬成員函數或輔助函數的運算符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.