2012-04-06 57 views
1

我试图让一个运算符,将允许我添加一个整数到我的类之一,但我有麻烦如下。二元运算符重载和polymorpism

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; 
} 

运营商实现所以我有一个载体,我试图来遍历它和所有的值添加到一个整数。但是,即使那些Derived类型也不会更改总和。

如何使运算符重载多态?

+0

围绕整个想法有一些有趣的气味,但无论如何,您应该提供* vector *的定义。第一个潜在的问题是所有的对象都被切成了“Base”... – 2012-04-07 00:32:10

回答

0

这是一位不错的博士。 dobbs为您的问题提出3种解决方案的文章http://drdobbs.com/cpp/200001978 其中之一,我在想同样的事情,就是您可以依靠虚拟成员函数或辅助函数的操作符。