任何人都可以向我解释我在这里做错了什么吗?
struct X {
int x{};
explicit X(int x) : x(x) {}
virtual X &operator++() = 0;
};
struct OK : X {
int ok{};
explicit OK(int ok) : X(ok), ok(ok) {}
X &operator++() override {
ok += 10;
return *this;
}
};
struct MU : X {
int mu{};
explicit MU(int mu) : X(mu), mu(mu) {}
X &operator++() override {
mu *= 5;
return *this;
}
};
int main() {
X *x_base = new OK(0);
++x_base;
std::cout << x_base->x;
return 1;
};
我想做的就是将多态性的思想用于运算符,特别是运算符++。我想要这样的结果:
Base* base = new Derivate();
++base <--- the ++ should be called from the Derivate class
Base* base2 = ned Derivate_2();
++base <--- the ++ should be called from the Derivate_2 class
更新:
我的问题目前的解决方案是使用 ++(*base) 我已经知道了。
但是有没有其他方法可以做++base而不是++(*base)?
感谢您的帮助:)
最佳答案
在这两行中,
X *x_base = new OK(0);
++x_base;
您创建一个指向新实例的指针,然后递增指针,而不是指针对象。永远不会调用类层次结构的增量运算符,而是调用指针的内置增量运算符。您可以通过首先取消引用指针来解决此问题:
++*x_base; // or ++(*x_base), might be more readable
您还可以使用引用而不是指针,这允许在不需要取消引用指针的情况下使用递增语法,例如
OK ok(0);
X& x_base = ok;
++x_base; // now, x_base is a reference, no need to dereference it
请注意,调用的运算符重载的实现不会更改 X::x
的值. std::cout << x_base->x;
在递增之后表明您希望该值不为零。
关于c++ - 如何覆盖多态性的运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54746008/