c++ - C++中不同数据类型的运算符重载
问题描述
以此为例:
float operator+(int a, float b)
{
Return b + (float)a;
}
void main()
{
int a = 10;
float b = 2.5f;
float c;
c = a + b; //works as intended
c = b + a; //results in type mismatch error
}
所以我的问题是:有没有办法在不定义第二个函数的情况下让参数被双向接受?
解决方案
It is not possible to overload operators for fundamental types. You should only overload operators for classes that you have defined.
A solution for overloading a binary operator for your own class with heterogeneous arguments symmetrically, is to define the operator for first type, and make the second type implicitly convertible to the first.
推荐阅读
- javascript - 如何根据用户选择在 JS 中再次重复我的程序?
- reactjs - 如何在 React 中处理 this.props.location.satate null 实例?
- regex - 在第一个实例中停止正则表达式(awk)
- sql - 我的 groupBy 没有在 laravel7 中将数据分组为 2 列
- python - 对熊猫中特定单元格下的值求和?
- jquery - 我如何处理数组中给出的这个错误,我希望在我的引导警报中填充错误
- azure - 主动消息端点的身份验证
- php - 为什么我的 PHP 网站没有呈现任何 CSS 或链接?
- vue.js - 动态创建的 vue 组件没有 $store 参数如何在创建时手动添加
- javascript - 如何将 0000 转换为数组?在Javascript中