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

Incremental operator overload in an abstract class C++

本文关键字:运算符 重载 C++ 抽象类      更新时间:2023-10-16
#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;
}

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

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