ProDeveloperTutorial.com

教程和编程解决方案
菜单
  • Shell脚本
  • 系统设计
  • Linux系统编程
  • 4g LTE
  • 编码问题
  • C
  • C ++
  • DSA
  • GIT

CPP第51章:CPP操作员重载教程

前开发者教程 2020年2月26日
如前几章所述,我们能够执行函数重载。同样,我们也可以重载运算符“+, -, =, *”我们将此概念称为运算符重载。

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+章
分享
电子邮件
鸣叫
领英
Reddit
绊倒
Pinterest的
上一篇文章
下一篇

关于作者

前开发者教程

每天我们都会讨论竞争性编程问题,请加入我们的网站:   电报频道

ProDeveloperTutorial.com

教程和编程解决方案
版权© 2020 ProDeveloperTutorial.com
从以下课程获得热门课程: 教育性的

      <kbd class="luWVkKF"></kbd>




        1. <small id="nDgarlI" class="ntMowMB"></small>