开发者

Inheriting operator +()

开发者 https://www.devze.com 2023-03-07 17:25 出处:网络
How to inherit overloaded operator +()? For example, I have two classes: class Bin : public Number<2, 256>

How to inherit overloaded operator +()?

For example, I have two classes:

class Bin : public Number<2, 256>
{
public:
    Bin(const char* number = NULL) :
        Number(number)
    {}
};

and

template <unsigned int BASE, unsigned int ORDER>
class Number
{
private:
    ...

public:
    Number(const char开发者_如何转开发* number = NULL) {
        ...
    }

    const Number& operator +=(const Number& number) {
        ...
    }

    Number operator +(const Number& number) const {
        Number result = *this;
        return result += number;
    }
};

operator +() returns Number. But I want to do:

Bin firstNum("101010111010");
Bin secondNum("1101011101");
Bin result = firstNum + secondNum;

Type of (firstNum + secondNum) - Number<2, 256> not Bin. Must I overload +() in every inheritor?


Consider what would need to happen in a slightly more complicated example than yours, where the derived class Bin has its own member variables. How could the base-class function possibly know what to do in order to create the return value? And what would it do in "mixed-mode" additions? (e.g. if one argument was a Bin, and the other was a Blah).

So yes, you will need to define specific operators everywhere that you want specific behaviour. Note that this is true not just of overloaded operators, but member functions in general.


It would probably be easier to just duplicate the implementation for operator+ in all derived classes. However, if you're feeling adventurous you could use the curiously recurring template pattern to enforce type consistency in your Number template class.


Can't be done, operators can't be made to be virtual(i.e. inherited). NOT directly at least.

You can do this:

class Base {
public:
   Base operator+(const Base& addend) { return addOp(addend) ; }
private:
   virtual Base addOp(const Base& addend) ;
} ;

and then override addOp to your heart's content. However you NEED to make sure that anything that inherits can return a 'Base' that will work with anything else. This gets to be pretty complicated pretty fast.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号