2025年作数的类型

作数的类型超载的 减法运算符 也很简单 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 class Cents private

大家好,我是讯享网,很高兴认识大家。 超载的 减法运算符 -) 也很简单
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 class Cents { private: int m_nCents; public: Cents(int nCents) { m_nCents = nCents; } // overload Cents + Cents friend Cents operator+(const Cents &c1, const Cents &c2); // overload Cents - Cents friend Cents operator-(const Cents &c1, const Cents &c2); int GetCents() { return m_nCents; } }; // note: this function is not a member function! Cents operator+(const Cents &c1, const Cents &c2) { // use the Cents constructor and operator+(int, int) return Cents(c1.m_nCents + c2.m_nCents); } // note: this function is not a member function! Cents operator-(const Cents &c1, const Cents &c2) { // use the Cents constructor and operator-(int, int) return Cents(c1.m_nCents - c2.m_nCents); }

讯享网

重载乘法操作符(*)和除法运算符(/)被定义为算子和算子/功能一样简单。

重载运算符的操作数的类型

经常的情况是,你想要你的重载操作符的操作数是与不同类型的工作。例如,如果我们有仙(4),我们可能要添加整数6到这来产生结果美分(10)。


讯享网

当C++计算表达式x + y,x和y是第一个参数,成为第二个参数。当X和Y具有相同的类型,它不如果你加X + Y或y + x -无论是物质,运算符+相同的版本被称为。然而,当操作数具有不同的类型,x + y y + X是不相同的

例如,仙(4)+ 6将调用操作符+(美分,int),和6美分(4)将调用操作符+(int,仙)。因此,每当我们过载对不同类型的操作数的二元操作符,我们真的需要写两个功能-一个用于每个案例。这里是一个例子:


小讯
上一篇 2025-03-07 21:29
下一篇 2025-02-15 12:59

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/58624.html