如前几章所述,我们能够执行函数重载。同样,我们也可以重载运算符“+, -, =, *”我们将此概念称为运算符重载。
Why do we need 算子 overloading?
考虑一个简单的示例:通常,我们使用算术加法运算符来添加整数。但是,有时需要添加或连接2个字符串。或添加同一类的2个不同对象的数据成员。在这种情况下,您可能会超载“+”字符串或类对象的运算符。
然后,编译器将决定要调用的适当函数。
运算符重载的语法或如何在C ++中重载运算符?
句法:
class ClassName { public: <return_type> 算子 <symbol> (arguments) { //function body } };
For 算子 overloading, we need to use “operator” keyword.
在行中“<return_type> 算子 <symbol> (arguments)”.
<return_type> is the return type.
“operator” is the keyword used to define 算子 overloading
<symbol> 符号 is the 算子 符号 you need to override like “+, -, =, *”
arguments:它们是您要传递给函数的参数。
Points to remember for 算子 overloading in C ++:
1.运算符重载只能用于用户定义的类型(类,结构)。不能用于内置类型。
2. Below 算子s cannot be overloaded in C ++:
::,。 ,。*,?:
3.编译器将自动覆盖=和&默认为运算符。
让我们借助几个示例来了解运算符重载:
1.简单“++” 算子 overloading.
#include <iostream> using namespace std; class MyClass { private: int num; public: MyClass(): num(5){ } void 算子 ++ () { cout<<"The value of num before increment is "<<num<<endl; num = num + 1; cout<<"The value of num after increment is "<<num<<endl; } }; int main(void) { MyClass obj; ++obj; }
输出:
The value of num before increment is 5 The value of num after increment is 6
2.简单“+”操作符重载,添加来自2个不同对象的数据成员。
#include <iostream> using namespace std; class MyClass { private: int num_1; int num_2; public: MyClass(int a, int b): num_1(a), num_2(b){ } friend MyClass 算子 + (MyClass &obj1, MyClass &obj2); void display() { cout<<"The value of num_1 "<<num_1<<" The value of num_2 "<<num_2<<endl; } }; MyClass 算子 + (MyClass &obj1, MyClass &obj2) { return MyClass(obj1.num_1+obj2.num_1, obj1.num_2+obj2.num_2); } int main(void) { MyClass obj_1(10, 20); MyClass obj_2(30, 40); MyClass obj_3 = obj_1 + obj_2; obj_3.display(); }
输出:
The value of num_1 40 The value of num_2 60
该网站上可用的教程列表:
C编程20+章 | C ++编程80+章 |
100多个编码问题 | 数据结构和算法85+章 |
系统设计20+章 | Shell脚本编写12章 |
4g LTE 60+章节 | 最常见的编码问题 |
5G NR 50+章 | Linux系统编程20+章 |