繁体   English   中英

抽象类中的c ++重载运算符

[英]c++ Overload operator in abstract class

我有下面的界面:

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

和抽象类:

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

而且,我有这个课:

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

operator +原型无法修改。

我的问题是我无法创建添加功能。 我尝试了这个:

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

但是我的编译器告诉我:错误:在初始化时无法将B转换为A * 实际上,我无法获得B来添加它们。

操作员不能是虚拟的(从技术上讲,他们可以,但是这是灾难的根源,会导致切片,客户端代码中怪异的算术表达式以及无理谋杀的可爱小海豹)。

您的C::add应该看起来像这样:

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

而且,您的老师应该了解不滥用内存分配,不滥用虚拟函数,不施加虚拟运算符以及C ++类接口设计中的好与坏做法-包括用于重载算术运算符的正确函数签名)。

firstsecond都是指针变量和保持地址。 而且您无法添加两个地址。

first + second不调用您的运算符重载函数,请尝试使用*first + *second

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

在这里,您尝试将A *指针(由operator +返回)分配给B *指针。 您必须强制转换结果。 像这样:

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

编辑:不是您应该以这种方式使用运算符重载。 utnapistim为此提供了一个很好的答案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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