IE盒子

搜索
查看: 104|回复: 0

C++重载运算符这么简单

[复制链接]

7

主题

10

帖子

23

积分

新手上路

Rank: 1

积分
23
发表于 2023-3-29 01:12:27 | 显示全部楼层 |阅读模式
前言

  所谓重载,就是赋予新的含义。函数重载(Function Overloading)可以让一个函数名有多种功能,在不同情况下进行不同的操作。运算符重载(Operator Overloading)也是一个道理,同一个运算符可以有不同的功能。

  运算符重载的本质是函数重载,是实现多态的重要手段,为用户提供了一个直观的接口。调用运算符操作自定义数据类型其实就是调用运算符函数。运算符重载使用同样的运算 符,可以操作不同的数据,增强了C++的可扩充性,使代码更加直观、易读,便于对对 象进行各种运算操作。

运算符重载格式

returnType operator symbol(parameters)

{
    function implement;
}
  operator是关键字,专门用于定义重载运算符的函数。我们可以将operator 运算符名称这一部分看做函数名.
  在开发中,+ - * / () []等符号经常需要重载。

运算符函数和普通函数有什么区别?

  运算符函数与普通函数相同。唯一的区别是,运算符函数的名称始终是运算符关键字后跟运算符的符号,并且在使用相应的运算符时调用运算符函数。
在类中重载“()”

#include <iostream>
#include <string>
class testOverload{


public:
    int operator()(std::string str) {
        std::cout<<str<<std::endl;
        return 0;
    }
};
int main(){

    testOverload()("hello");
}
控制台输出
hello
  此例中,重载了(),参数为字符串,testOverload()是构造一个临时对象,然后调用()运算符,传入"hello"字符串,期待调用operator()("hello"),控制台的输出符合预期。

《C++ Primer》和《Effective C++》是C++开发者必不可少的书籍,如果你想入门C++,以及想要精进C++开发技术,这两本书可以说必须要有。此外,《Linux高性能服务器编程》以及《Linux多线程服务端编程:使用muduo C++网络库》.(陈硕)》是快速提高你的linux开发能力的秘籍。在网上搜索相关资源也要花费一些力气,需要的同学可以关注公众号【程序员DeRozan】,回复【1207】快速免费领取~
全局重载"()"

在全局范围内为自定义class重载(),如果运算符里面需要访问私有数据,则需要将重载函数定义为友元函数。例如:

#include <iostream>
using namespace std;

class A
{
private:
int x, y;
public:
A(int x1 = 0, int y1 = 0)
{
  x = x1;
  y = y1;
}
friend A operator+(const A& a, const A& b);
void show()
{
  cout << "x=" << x << "," << "y=" << y << endl;
}
};
A operator+(const A& a, const A& b)
{
return A(a.x + b.x, a.y + b.y);
}
int main()
{
A a1(1, 2), a2(3, 4);
A c;
c = a1 + a2;
c.show();
return 0;
}
转自:https://blog.csdn.net/qq_52905520/article/details/127178512
结果输出
x=4,y=6
可以支持运算符重载的运算符

Binary Arithmetic:        +, -, *, /, %
Unary Arithmetic:         +, -, ++, —
Assignment:        =, +=,*=, /=,-=, %=
Bitwise:        & , | , << , >> , ~ , ^
De-referencing:        (->)
Dynamic memory allocation,De-allocation:New, delete  
Subscript:        [ ]
Function call: ()  
Logical:         &,  | |, !
Relational:>, < , = =, <=, >=
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表