抽象类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;
}
但是在这种情况下,它必须返回指向对象的指针,因为它是一个抽象类。
不,它没有。 实际上,参考更好。 除非您按值返回,否则您不会遇到切片。
相关文章:
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- <T> 通过模板化运算符重载将 std::complex 乘以双倍
- C++20概念:需要运算符重载
- 使用赋值运算符重载从类中返回jobject
- 在运算符重载定义中使用成员函数(const错误)
- 字节到位运算符重载C++
- 为什么在运算符重载时需要参考?
- 类中 c++ 的运算符 + 重载
- 算术复合运算符重载为非成员
- 运算符重载 (+),用于添加两个具有 C++ 的数组
- 交换运算符 + 重载会导致无限递归
- 如何理解新的运算符重载?
- 向量保持复数的运算符重载
- 如何创建运算符重载?
- 链接列表运算符重载没有打印出我想要的内容
- C++:需要帮助了解运算符重载错误
- 使用模板化运算符重载 XOR 运算符失败
- 如何确保接受的C++模板类型使运算符重载?
- 运算符重载使用运算符+添加类模板