抽象类C ++中的增量运算符重载

时间:2016-05-20 18:20:09

标签: c++ overloading increment operator-keyword

#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&amp; operator ++(int dummy)但在这种情况下,它必须返回一个指向对象的指针,因为它是一个抽象类。如果不在每个继承的类中编写单独的代码,我有什么方法可以做到这一点吗?

这给出了5,5而不是5,6的输入。

2 个答案:

答案 0 :(得分:3)

算术运算符不能很好地处理多态类,除非你将多态实现包装在非多态包装中。

代码中的注释解释了基类的添加:

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

答案 1 :(得分:0)

  

但在这种情况下,它必须返回一个指向对象的指针,因为它是一个抽象类。

不,它没有。实际上参考更好。除非按价值返回,否则你不会遇到切片。