带有抽象继承的后缀运算符++

Myo*_*one 2 c++ inheritance operator-overloading abstract

我想在结构层次结构(抽象基数A和子B)中实现前缀和后缀运算符++.当只在基类中实现前缀时,这很好.但是,在子类中实现后缀版本时(因为它不能在抽象类中实现),它不起作用.

struct A {
    virtual A& operator++(){std::cout << "A: prefix ++" << std::endl; return *this;}
    virtual void foo() = 0;
};

struct B : A {
    void foo() override {};
    //virtual B& operator++() override {std::cout << "B: prefix ++" << std::endl; return *this;}
    //B operator++(int i) {std::cout << "B: postfix ++" << std::endl; return *this;}
};

int main(int argc, const char * argv[]) {
    B b;
    ++b; // Compile error here if I implement postfix in B
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

问题是我想避免重复代码,因为所有派生类都将以相同的方式使用operator ++,所以最好不要在各自的类中实现它们.使用抽象类的重点是避免这种情况!

我的问题是:解决这个问题最优雅的方法是什么?

编辑.错误消息:无法递增类型'B'的值

Chr*_*rew 6

问题是operator++派生类中的名称隐藏了基类中的名称.尝试将以下内容添加到B:

using A::operator++;
Run Code Online (Sandbox Code Playgroud)

您可能会发现很难使后增量函数具有多态性.协变返回类型不起作用.

现场演示.