簡體   English   中英

抽象類C ++中的增量運算符重載

[英]Incremental operator overload in an abstract class C++

#include <iostream>
using namespace std;

class A{
private:
  double price;
public:
  A(double p):price(p){
  }
  virtual double abstractExample() = 0;
  A* operator++(int dummy){
    this->price = this->price + 1;
    return this;
  }
  virtual ~A(){
  }
  void print(){
    cout << price << endl;
  }
};

class B : public A {
  public:
    B(int p): A(p){
    }
    double abstractExample(){
        return 1;
    }
};

int main(){
  B* b = new B(5);
  b->print();
  b++->print();

  return 0;
}

所以我有了這個抽象類A。我想重載++運算符。 通常,我只寫A&運算符++(int dummy),但是在這種情況下,我必須返回指向對象的指針,因為它是抽象類。 沒有任何方法可以在每個繼承的類中編寫單獨的代碼而無需這樣做?

輸入為5、5,而不是5、6。

除非將多態實現包裝在非多態包裝中,否則算術運算符不能很好地與多態類一起使用。

代碼中的注釋說明了對基類的補充:

#include <iostream>
#include <memory>

using namespace std;

class A{
private:
  double price;
public:
  A(double p):price(p){
  }
  virtual double abstractExample() = 0;

  void increment()
  {
    this->price = this->price + 1;
  }

  // see below. clone in base must be abstract if the base class
  // is abstract. (abstractExample is pure so that's that)
  virtual std::unique_ptr<A> clone() const =0;

  virtual ~A(){
  }

  void print(){
    cout << price << endl;
  }
};

class B : public A {
  public:
    B(int p): A(p){
    }
    double abstractExample(){
        return 1;
    }

  std::unique_ptr<A> clone() const override
  {
    return std::make_unique<B>(*this);
  }

};

struct AB 
{
  AB(std::unique_ptr<A> p) : _ptr(std::move(p)) {}

  // pre-increment is easy
  AB& operator++() {
    _ptr->increment();
  }

  // post-increment is trickier. it implies clonability.
  AB operator++(int) {
    AB tmp(_ptr->clone());
    _ptr->increment();
    return tmp;
  }

  void print() {
    _ptr->print();
  }

  std::unique_ptr<A> _ptr;
};

int main(){
  AB b(std::make_unique<B>(5));
  b.print();

  // pre-increment
  (++b).print();

  // post-incrememnt will involve a clone.
  (b++).print();

  return 0;
}

但是在這種情況下,我必須返回一個指向對象的指針,因為它是一個抽象類。

不,不是。 引用實際上更好。 除非您按值返回,否則您不會遇到切片問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM