大家好,欢迎来到IT知识分享网。
在C ++中,我们可以使运算符为用户定义的类工作。这意味着C ++能够为运算符提供数据类型的特殊含义,这种能力称为运算符重载。

例如,我们可以在String之类的类中重载运算符’+’,以便仅使用+就可以连接两个字符串。
算术运算符可能会重载的其他示例类是复数,小数,大整数等。
一个简单而完整的例子
#include<iostream> using namespace std; class Complex { private: int real, imag; public: Complex(int r = 0, int i =0) {real = r; imag = i;} // This is automatically called when '+' is used with // between two Complex objects Complex operator + (Complex const &obj) { Complex res; res.real = real + obj.real; res.imag = imag + obj.imag; return res; } void print() { cout << real << " + i" << imag << endl; } }; int main() { Complex c1(10, 5), c2(2, 4); Complex c3 = c1 + c2; // An example call to "operator+" c3.print(); }
输出:
12 + i9
运算符功能和普通功能有什么区别?
运算符功能与普通功能相同。唯一的区别是,运算符的名称始终是运算符关键字,后跟运算符的符号,并且在使用相应的运算符时会调用运算符功能。
以下是全局运算符功能的示例:
#include<iostream> using namespace std; class Complex { private: int real, imag; public: Complex(int r = 0, int i =0) {real = r; imag = i;} void print() { cout << real << " + i" << imag << endl; } // The global operator function is made friend of this class so // that it can access private members friend Complex operator + (Complex const &, Complex const &); }; Complex operator + (Complex const &c1, Complex const &c2) { return Complex(c1.real + c2.real, c1.imag + c2.imag); } int main() { Complex c1(10, 5), c2(2, 4); Complex c3 = c1 + c2; // An example call to "operator+" c3.print(); return 0; }
我们可以让所有运算符超负荷吗?
除了少数运算符之外,几乎所有运算符都可以重载。以下是不能重载的运算符的列表。
。(点运算符) :: ?: 大小
关于运算符重载的要点
1)为了使运算符重载起作用,至少一个操作数必须是用户定义的类对象。
2) 赋值运算符:编译器会自动为每个类创建一个默认的赋值运算符。默认的赋值运算符确实将右侧的所有成员分配到左侧,并且在大多数情况下都可以正常工作(此行为与复制构造函数相同)。
3) 转换运算符:我们还可以编写可用于将一种类型转换为另一种类型的转换运算符。
#include <iostream> using namespace std; class Fraction { int num, den; public: Fraction(int n, int d) { num = n; den = d; } // conversion operator: return float value of fraction operator float() const { return float(num) / float(den); } }; int main() { Fraction f(2, 5); float val = f; cout << val; return 0; }
输出:
0.4
重载的转换运算符必须是成员方法。其他运算符可以是成员方法或全局方法。
4)任何可以用单个参数调用的构造函数都可以用作转换构造函数,这意味着它也可以用于隐式转换为正在构造的类。
#include<iostream> using namespace std; class Point { private: int x, y; public: Point(int i = 0, int j = 0) { x = i; y = j; } void print() { cout << endl << " x = " << x << ", y = " << y; } }; int main() { Point t(20, 20); t.print(); t = 30; // Member x of t becomes 30 t.print(); return 0; }
输出:
x = 20,y = 20 x = 30,y = 0
我们很快将讨论一些重要运算符的重载,欢迎持续关注~
以上就是今天的全部内容了。每日分享小知识,希望对你有帮助~
另外如果你想更好的提升你的编程能力,学好C语言C++编程!弯道超车,快人一步!笔者这里或许可以帮到你~
编程学习书籍分享:

编程学习视频分享:

分享(源码、项目实战视频、项目笔记,基础入门教程)
欢迎转行和学习编程的伙伴,利用更多的资料学习成长比自己琢磨更快哦!
点击下方【了解更多】获取更多学习资料帮助你学习成长哦~
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://haidsoft.com/188536.html