简体   繁体   中英

Abstract class overloading arithmetic operator

I'm learning c++ and I'm trying to do some polymorphism and operator overloading and I'm having some problems.

What I'm doing here is an abstract base class called Number and a derivated class called MyInt, I need to overload operator+,- in order to operate with MyInt numbers, MyDouble numbers... etc

After reading many posts I got stuck in this error error: invalid operands of types 'Number*' and 'Number*' to binary 'operator+' cout << n + m << endl; How can I make this work?

I know this works using templates but I can't use it here because the point of this excercise is to create something like MyStack<Number*> to hold different data types

#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

class Number {
public:
    virtual Number* operator+(Number* n) = 0;
    virtual string toString() = 0;
    friend ostream& operator<<(ostream& os, Number* n){ 
        return os << n->toString();
    }
};

class MyInt: public Number{
public:
    int value;
    MyInt(int e){
        value = e;
    }
    virtual ~MyInt(){}
    int getNum(){ return value;}

    Number* operator+(Number* n){
        MyInt* a = (MyInt*) n;        
        return new MyInt(value + a->value);
    }

    string toString(){
        ostringstream oss;
        oss << value;
        return oss.str();
    }
 };

int main(int argc, char** argv) {
    Number* n = new MyInt(5);
    Number* m = new MyInt(3);

    cout << "N: " << n << endl;
    cout << "M: " << m << endl;


    cout << n + m << endl;

    return 0;
}

You did it very wrong. The immediate source of error is that both your n and m are pointers, and yet member operator+ would want an object to be invoked on.

You could, in theory, perform a double dispatch (otherwise the syntax would be just ugly):

// define operator+ as a free function
Number* operator+(Number* lhs, Number* rhs) {
    return lhs->operator+(rhs);
}

However, while plus will be called for lhs will be called virtually, rhs will remain an abstract type. You will not be able to figure out what it is unless you do dynamic_cast for it - and that's just ugly. In general, your example is simply not a good case for dynamic polymorphism.

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