前言
c++的一大特点就是重载,重载使得程序更加的简洁,函数可以重载,运算符也可以重载,运算符的重载主要是面向对象之间的。
一、运算符重载是什么?
运算符的操作对象可以是基本的数据类型,也可以重新定义的运算符,赋予运算符新功能,对类对象进行相关操作。在类中中重新定义运算符,赋予运算符新功能以适应自定义数据结构类型的运算,就成为运算符重载。
二、使用步骤
1.运算符语法:
返回值类型 operator 运算符名称 (参数列表)
{…//函数体
}
`
2.加号重载运算符
成员函数重载+号和全局函数重载+号不能同时存在,要注释掉一个
代码如下(示例):
#include<bits/stdc++.h>
using namespace std;
class person
{
public:
// //成员函数重载+号
// person operator+(person &p)
// {
// person t;
// t.A=this->A+p.A;
// t.B=this->B+p.B;
// return t;
// }
//
int A;
int B;
};
//全局函数重载+号
person operator+(person &p1,person &p2)
{
person t;
t.A=p1.A+p2.B;
t.B=p1.B+p2.B;
return t;
}
void test()
{
person p1;
p1.A=10;
p1.B=10;
person p2;
p2.A=20;
p2.B=20;
person p3=p1+p2;
cout<<"p3.A="<<p3.A<<endl;
cout<<"p3.B="<<p3.B<<endl;
}
int main()
{
test();
return 0;
}
成员函数重载本质调用:person p3=p1.operator+(p2);
全局函数重载本质调用:person p3=operator+(p1,p2);
程序里面写的是简略形式
数据类型和定义的不一样是不能进行运算
3.左移运算符重载
在 C++中,ostream表示输出流,英文”output stream“的简称。在 C++中常见的输出流对象就是标准输出流cout,很少自定义ostream的对象,更多的是直接使用cout。
我们重载了<<操作符,让其能够正常输出。
OK,这样就可以直接输出cout << point;
该方法还可以扩展到其他很多地方,对自定义的类型进行输出时特别管用,写法都是一样的,只要重载<<操作符,配合ostream一起使用即可。
#include<bits/stdc++.h>
using namespace std;
class person
{
public:
int A;
int B;
};
ostream & operator<<(ostream &cout,person &p) //本质 operator<<(cout,p)简化cout<<p;
{
cout<<"A="<<p.A<<" B="<<p.B<<endl;
return cout;
}
void test()
{
person p1;
p1.A=10;
p1.B=10;
cout<<p1<<endl;
}
int main()
{
test();
return 0;
}
4.递增运算符重载
#include<bits/stdc++.h>
using namespace std;
//重载递增运算符
//自定义整形
class MyInt
{
friend ostream& operator<<(ostream& cout, MyInt myint);
public:
MyInt()
{
m_Num = 0;
}
// 重载后置++运算符
// int代表占位参数,可以用于区分前置和后置
MyInt operator++(int)//注意这里返回值而不是引用
{
//先 记录当时结果
MyInt temp = *this;
//后 递增
m_Num++;
//最后返回记录结果
return temp;
}
private:
int m_Num;
};
//重载左移运算符
ostream& operator<<(ostream& cout, MyInt myint)
{
cout << myint.m_Num;
return cout;
}
void test02()
{
MyInt myint;
cout << myint++ << endl;
cout << myint << endl;
}
int main()
{
test02();
return 0;
}
总结
提示:这里对文章进行总结:
例如:以上就是今天要讲的内容,本文仅仅简单介绍了pandas的使用,而pandas提供了大量能使我们快速便捷地处理数据的函数和方法。