C++中通过运算符重载实现对对象的一些运算符操作
加号运算符重载
#include<iostream>
#include <string>
using namespace std;
class Person
{
public:
int m_A;
int m_B;
public:
//列表初始化
Person() {};
Person(int a,int b)
{
this->m_A = a;
this->m_B = b;
}
//加号运算符重载
Person operator+(Person& p1)
{
Person temp;
temp.m_A = this->m_A + p1.m_A;
temp.m_B = this->m_B + p1.m_B;
return temp;
}
};
void test01()
{
Person p1(10, 20);
Person p2(10, 20);
Person p3 = p1 + p2;
cout << p3.m_A << p3.m_B << endl;
}
int main()
{
test01();
}
移位运算符重载
#include<iostream>
#include<string>
using namespace std;
class Person
{
friend ostream& operator<<(ostream& out, Person& p);
public:
Person() {};
Person(int a, int b)
{
this->m_A = a;
this->m_B = b;
}
private:
int m_A;
int m_B;
//重载移位运算符
};
ostream& operator<<(ostream& out, Person& p)
{
out << p.m_A << " " << p.m_B << " ";
return out;
}
void test01()
{
Person p1(10, 20);
cout << p1 << "Hello,World" << endl;
}
int main()
{
test01();
}
递增运算符重载
#include<iostream>
#include<string>
using namespace std;
class MyInteger
{
friend ostream& operator<<(ostream& output, MyInteger i);
public:
//默认构造函数
MyInteger()
{
My_Num = 0;
}
//重载前置++运算符
MyInteger& operator++()
{
++My_Num;
return *this;
}
//占位参数,重载后置++运算符
MyInteger operator++(int)
{
//先存储当前值
MyInteger temp = *this;
//实现++
My_Num++;
//返回之后未加的值
return temp;
}
private:
int My_Num;
};
//重载移位运算符
ostream& operator<<(ostream& output, MyInteger i)
{
output << i.My_Num << endl;
return output;
}
void test01()
{
MyInteger i;
cout << i++ ;
cout << i;
}
int main(char argc,int** argv)
{
test01();
}
赋值运算符重载
#include<iostream>
#include<string>
using namespace std;
class Person
{
public:
//有参构造函数
Person(int age)
{
m_age = new int(age);
}
//重载赋值运算符
Person& operator=(Person& p)
{
if (m_age != NULL)
{
delete m_age;
m_age = NULL;
}
//深拷贝解决重复释放堆区内存带来的程序崩溃问题
m_age = new int(*p.m_age);
return *this;
}
//析构
~Person()
{
if (m_age != NULL)
{
delete m_age;
m_age = NULL;
}
}
//开辟一个堆区
int* m_age;
};
void test01()
{
Person p1(18);
Person p2(20);
Person p3(30);
p3 = p2 = p1;
cout << *p1.m_age << endl;
cout << *p2.m_age << endl;
cout << *p3.m_age << endl;
}
int main()
{
test01();
}
关系运算符重载
#include<iostream>
#include<string>
#include<vector>
using namespace std;
class Person
{
public:
//默认构造函数
Person()
{
m_Age = 0;
}
//有参构造函数
Person(string name,int Age)
{
this->m_name = name;
this->m_Age = Age;
}
//重载等于运算符
bool operator==(Person& p)
{
if (this->m_name == p.m_name && this->m_Age == p.m_Age)
{
return true;
}
else
{
return false;
}
}
string m_name;
int m_Age;
};
void test01()
{
Person p1("蔡晨雨",18);
Person p2("刘慧", 17);
if (p1 == p2)
{
cout << "两人的姓名与年龄相等" << endl;
}
else
{
cout << "两人的姓名与年龄不相等" << endl;
}
}
int main()
{
test01();
}
函数运算符重载
因为与调用函数的结构非常类似,因此也叫仿函数,后续STL中会用到
#include<iostream>
#include<string>
#include<vector>
using namespace std;
class Myprint
{
public:
void operator()(string text)
{
cout << text << endl;
}
};
void test01()
{
Myprint myprint;
myprint("Hello World");
}
int main()
{
test01();
}