前缀和后缀操作符继承

Prefix and postfix operators inheritance

本文关键字:继承 操作符 后缀 前缀      更新时间:2023-10-16

考虑以下代码:

// Only prefix operators
struct prefix
{
    prefix& operator--() { return *this; }
    prefix& operator++() { return *this; }
};
// Try to represent prefix & postfix operators via inheritance
struct any : prefix
{
    any operator--(int) { return any(); }
    any operator++(int) { return any(); }
};
int main() {
    any a;
    a--;
    a++;
    --a; // no match for ‘operator--’ (operand type is ‘any’)
    ++a; // no match for ‘operator++’ (operand type is ‘any’)
    return 0;
}

我尝试创建一个类的层次结构。基类,只实现前缀自增/自减操作符。并在派生类中添加后缀版本。

但是,编译器找不到派生类对象的前缀操作。

为什么会发生这种情况,为什么前缀操作符不被继承?

执行以下命令,导入prefix类中隐藏的operator--operator++

struct any : prefix
{
    using prefix::operator--;
    using prefix::operator++;
    any operator--(int) { return any(); }
    any operator++(int) { return any(); }
};

现场演示

这可能是一个糟糕的想法,但至少它可以编译。