【问题标题】:Define new operator in c++ [duplicate]在c ++中定义新运算符[重复]
【发布时间】:2020-05-07 05:09:48
【问题描述】:

我们可以在 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++


【解决方案1】:

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

#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;
}

【讨论】:

  • 这令人困惑。你有一个对象,它看起来是一个int(从它的名字来看),但是有一个重载的 '%' 操作符,它的行为与 '%' int 的内置操作符相似但不同
  • @bolov 我同意。名称应该类似于 int_with_non_negative_mod。正如 Stroustrup 所说,“丑陋操作的丑陋符号”:-)。
猜你喜欢
  • 1970-01-01
  • 2011-01-19
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-09
  • 1970-01-01
相关资源
最近更新 更多