c++ - 在 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 的方法。
解决方案
您只能重载现有的运算符。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;
}
推荐阅读
- typescript - 如何限制打字稿的文字表达式只接受可用的属性?
- android - 致命异常:主进程:com.delegates.predelegatesapprider,PID:8258 java.lang.NoClassDefFoundError:
- android - 自定义背景资源在android中不起作用
- ios - swift如何让UILabel对齐到左上角
- reactjs - 我无法为元标记分配动态值?
- javascript - JQuery.Ajax() 不工作不确定脚本是否正确加载
- assembly - 是否可以在基于累加器的机器/ISA 中实现流水线操作?
- azure-active-directory - 免费 Office 帐户的无效授权错误
- python - 大熊猫汇总
- time-complexity - 内循环根据外循环增加的时间复杂度