c++ - 前缀和后缀运算符继承

标签 c++ inheritance operator-overloading postfix-operator prefix-operator

<分区>

考虑以下代码:

// 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(); }
};

Live demo

这可能是个糟糕的主意,但至少它会通过编译。

关于c++ - 前缀和后缀运算符继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24533210/

相关文章:

php - 扩展 Doctrine 对象类

python - 在 Django 中管理继承

c++ - 重载下标运算符 []

c++ - 模板化运算符的奇怪行为<<

c++ - 右键单击 QListWidget 上的按钮

c++ - glCreateShader 和 glCreateProgram 在 SDL 2 IOS 中返回 0

python - 是否可以在不需要重新定义属性的情况下覆盖父类(super class)的属性 setter

swift - 从 Swift 中的类型别名覆盖调用字符串相等运算符

c++ - boost::variant 单一存储保证

c++ - 从迭代器中获取 const_iterator