简体   繁体   中英

c++ Overload operator in abstract class

I have the folllowing interface:

class A
{
  public:
    virtual A * operator+(const A &rhs) const = 0;
}

And the abstract class :

class B : public A
{
  public:
    B(int val)
    {
      this->val = val;
    }

    virtual A * operator+(const A &rhs) const
    {
      return (new B(this->val + rhs.val));
    }
    int val;
}

Moreover, I have this class :

class C
{
  public:
    void add();
  private:
    std::stack<A *> Astack;
}

The operator+ prototype cannot be modified.

My issue is that I fails to create the add function. I tried this:

void    C::add()
{
  B first = *dynamic_cast<B *>(this->Astack.top()); // Error here
  this->Astack.pop();
  B second = *dynamic_cast<B *>(this->Astack.top()); // And here
  this->Astack.pop();
  B * res = first + second;
  this->Astack.push(res);
}

But my compiler tells me : error: cannot convert B to A * in initialization. In fact, I fails to obtain to B to add them.

Operators cannot be virtual (well, technically they can, but it's a recipe for disaster, causing slicing, weird arithmetic expressions in client code and the unwarranted murder of cute baby seals).

Your C::add should look similar to this:

void C::add() // assuming implementation is supposed to sum instances and 
              // add replace the contents of Astack with the sum
{
    A* x = Astack.top();
    Astack.pop();
    while(!Astack.empty()) {
        A* y = Astack.top();
        Astack.pop();

        A* z = (*x) + (*y);
        delete x;
        delete y;

        x = z; // latest result will be in x on the next iteration
    }
    Astack.push(x);
}

Also, your teacher should learn about not abusing memory allocation, not abusing virtual functions, not imposing virtual operators and good and bad practices in C++ class interface design - including the correct function signatures for overloading arithmetic operators).

first and second both are pointer variable and holding address. and you cant add two address.

first + second is not calling you operator overloading function, try by using *first + *second

B * res = first + second;  // Error here !

Here you try to assign a A* pointer (which is returned by operator+) to a B* pointer. You have to cast the result. Something like that:

B * res = dynamic_cast<B*>(first + second);

Edit: not that you should use operator overloading in this way. utnapistim gave a good answer about that.

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