簡體   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