首页 > 解决方案 > 在 C++ 中定义新运算符

问题描述

我们可以在 C++ 中定义自己的运算符吗?

我需要将 a%%b 定义为 (a%b+b)%b,因为​​有时 a%b 会给出负值(-239%5=-4),我想要积极的提醒。因此,如果 a%b 为负数,则将 b 添加到 a%b 并返回该值。这可以简单地使用 (a%b+b)%b 来完成。我试过了

#define a%%b (a%b+b)%b

但它给出了错误。我们可以通过使用函数来做到这一点

int mod(int a, int b){
    return (a%b+b)%b;
}

但我想通过定义像我为“for”循环所做的那样来做到这一点

#define f(i,a,b) for(int i=a;i<b;i++)

请建议我一种将 a%%b 定义为 (a%b+b)%b 的方法。

标签: c++

解决方案


您只能重载现有的运算符。int但是,您可以用自己的类包装 an ,并operator%为此类重载。像这样

#include <iostream>

struct int_wrapper {
    explicit int_wrapper(int n) : n_(n)
    { }
    operator int() const {
        return n_;
    }
private:
    int n_;
};

int operator%(int_wrapper lhs, int_wrapper rhs) {
    return ((int)lhs % rhs + rhs) % rhs;
}

int main() {
    std::cout << (int_wrapper(-239) % int_wrapper(5)) << std::endl;
}

推荐阅读