C++运算符重载
一·.C++运算符重载之“+”号
1.成员函数实现运算符重载
//加号运算符重载
class classDemo {
public:
classDemo();
~classDemo();
//1.使用成员函数进行运算符重载:
classDemo operator+(classDemo &p);
int m_Aage;
int m_Bage;
private:
protected:
};
classDemo classDemo::operator+(classDemo &p) {
classDemo temp;
temp.m_Aage = this->m_Aage + p.m_Aage;
temp.m_Bage = this->m_Bage + p.m_Bage;
return temp;
}
2.使用全局函数实现运算符重载
//全局函数做运算符重载
classDemo operator+(classDemo &p1,classDemo &p2)
{
classDemo temp;
temp.m_Aage = p1.m_Aage + p2.m_Aage;
temp.m_Bage = p2.m_Bage + p2.m_Bage;
return temp;
}
void test_01()
{
classDemo cla_1;
classDemo cla_2;
//成员函数的本质调用:p3 = p1.operator+(p2);
//全局函数的本质调用:p3 = operator+(p1,p2);
//运算符重载也可以发生函数重载
classDemo cla_3 = cla_1 + cla_2;
cout << cla_3.m_Aage << " " << cla_3.m_Bage << endl;
}
二.C++运算符重载之“<<”号
//左移运算符只能用全局函数重载,若用成员函数重载,不能实现cout在左边
ostream &operator<<(ostream &cout,classDemo &p)
{
cout << p.m_Aage << " " << p.m_Bage;
return cout;
}
三.C++运算符之递增递减运算符
//递增运算符案例
class MyInteger
{
friend ostream &operator<<(ostream &cout,MyInteger &p);
public:
MyInteger(){
m_age = 0;
}
~MyInteger(){
}
//重载前置++运算符,返回引用为了一直对一个数据进行递增操作
MyInteger& operator++()
{
m_age++;
return *this;
}
//重载后置++运算符,(int)是一个占位符,与前置区别开来
MyInteger operator++(int)
{
//先记录当时的值
MyInteger temp = *this;
//再递增
m_age++;
//最后返回结果
return temp;
}
MyInteger& operator--()
{
m_age--;
return *this;
}
MyInteger--(int)
{
MyInteger temp = *this;
m_age--;
return temp;
}
private:
int m_age;
};
四.C++运算符之赋值运算符
//重载赋值运算符
class Person
{
public:
Person(int age){
m_age = new int(age);
}
~Person(){
if(m_age != NULL) {
delete m_age;
m_age = NULL;
}
}
int *m_age;
//赋值操作符重载
Person &operator=(Person &p1)
{
//判断是否有属性在堆区,如果有,先释放干净,然后再深拷贝;
if(m_age != NULL)
{
delete m_age;
m_age = NULL;
}
//开辟新空间--深拷贝
m_age = new int(*p1.m_age);
//返回对象本身
return *this;
}
};
五.C++运算符重载之”=“号
//赋值运算符重载
class Student_1
{
public:
Student_1(string name,int age){
m_age = age;
m_name = name;
}
bool operator==(Student_1 &stu)
{
if(this->m_name == stu.m_name && this->m_age == stu.m_age)
{
return true;
}
return false;
}
~Student_1(){}
int m_age;
string m_name;
};
六.C++运算符重载之函数调用运算符重载
1.函数运算符也可以重载
2.由于重载后的方式非常像函数,所以也称仿函数
3.仿函数没有固定的写法,非常灵活
void operator()(string test)
{
cout << test << endl;
}
int operator()(int a,int b)
{
return a+b;
}
//用法:
//创建对象
MyString mystring;
mystring("hahaha");
//匿名函数对象
MyAdd()(100,100);