简体   繁体   中英

Binary operator overloading and polymorpism

I'm trying to make an operator that will allow me to add an integer to one of my classes, but I'm having trouble as follows.

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

With the operator implementation of

int & operator+=(int & num, Base & b)
{
    return num;
}

int & operator+=(int & num, Derived & d)
{
    num += d.value_;
    return num;
}

So I have a vector and I'm trying to iterate through it and add all of the values to one integer. However, even those that are of type Derived won't change the sum.

How can I make the operator overloading polymorphic?

Here is a nice dr. dobbs article that presents 3 solutions to your problem http://drdobbs.com/cpp/200001978 One of them, and I was thinking the same thing, is that you can rely your operators on virtual member functions or auxiliary functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM