c++ - 如何覆盖多态性的运算符

标签 c++ polymorphism operator-overloading operators

任何人都可以向我解释我在这里做错了什么吗?

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/

相关文章:

c++ - clang/clang++ 在 Windows 中找不到 C/C++ 头文件?

c++ - 无法初始化指向具有基类右值的子类的指针

java - 如何消除 switch case 或 if-else ?并执行以下操作?

c++ - 如何将在重载 >> 运算符中输入的值插入 setter

c++ - 是否有默认为静态的成员函数?

c++ - C++ std::uniform_real_distribution<double> 应该只生成正数吗?

C++ CScrollView,如何滚动图像?

c++ - 旋转矩阵的方向 vector

Java:对于每个循环,迭代扩展对象

C# 运算符重载、重写字符串?