对于内置数据类型,编译器知道如何进行运算
但是对于自定义数据类型,编译器并不知道该如何运算
利用运算符重载可以解决这个问题
注意:运算符重载也可以发生函数重载
#include<iostream>
using namespace std;
// 加号运算符重载
class Person
{
public:
Person() {};
Person(int a, int b) :m_a(a), m_b(b)
{}
// 加号运算符重载(成员函数)
Person operator+(Person &p)
{
Person temp;
temp.m_a = this->m_a + p.m_a;
temp.m_b = this->m_b + p.m_b;
return temp;
}
int m_a;
int m_b;
};
Person operator+(Person &p1, Person &p2)
{
Person temp;
temp.m_a = p1.m_a + p2.m_a;
temp.m_b = p1.m_b + p2.m_b;
return temp;
}
// 运算符重载发生函数重载
Person operator+(Person &p1, int a)
{
Person temp;
temp.m_a = p1.m_a + a;
temp.m_b = p1.m_b + a;
return temp;
}
void test01()
{
Person p1(10, 10);
Person p2(20, 20);
Person p3 = p1 + p2;
cout << "p3.m_a = " << p3.m_a << endl;
cout << "p3.m_b = " << p3.m_b << endl;
// 本质:
// 成员函数本质:
// Person p3 = p1.operator+(p2);
// 全局函数本质
// Person p3 = operator+(p1, p2);
Person p4 = p1 + 10;
cout << "p4.m_a = " << p4.m_a << endl;
cout << "p4.m_b = " << p4.m_b << endl;
}
int main()
{
system("pause");
return 0;
}
对于内置数据类型,编译器知道如何运用cout进行<<运算符输出
对于自定义数据类型,无法输出
#include<iostream>
using namespace std;
// 左移运算符重载
class Person
{
friend ostream & operator<<(ostream &cout, Person &p);
public:
Person() {};
Person(int a, int b)
{
this->m_a = a;
this->m_b = b;
}
// 利用成员函数 实现运算符重载
/* void operator<<(ostream &cout)
{
}*/
private:
int m_a;
int m_b;
};
// 利用全局函数 实现<<运算符重载
ostream & operator<<(ostream &cout, const Person &p)
{
cout << "p.m_a = " << p.m_a << " p.m_b = " << p.m_b;
return cout;
}
void test01()
{
Person p1(10, 10);
//cout << "p1.m_a = " << p1.m_a << " p1.m_b = " << p1.m_b << endl;
//cout << p1 << endl;
//operator<<(cout, p1);
cout << p1 << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
#include<iostream>
using namespace std;
// 递增递减运算重载 ++ --
class MyInt
{
public:
MyInt()
{
m_Num = 0;
}
MyInt& operator++()
{
m_Num++;
return *this;
}
MyInt operator++(int)
{
MyInt temp = *this;
this->m_Num++;
return temp;
}
int m_Num;
protected:
private:
};
ostream &operator<<(ostream &cout,const MyInt &myint)
{
cout << myint.m_Num;
return cout;
}
/*void operator++() //前置++ 先++ 后返回
{
}*/
/*void operator++(int) //后置++ 先返回 后++
{
}*/
void test01()
{
MyInt myint;
cout << myint << endl;
cout << ++myint << endl; // 1
//cout << myint++ << endl; // 1
cout << myint << endl; // 2
}
void test02()
{
MyInt myint;
cout << myint << endl;
cout << myint++ << endl;
// operator<<(cout, myint++);
cout << myint << endl;
}
int main()
{
// test01();
test02();
system("pause");
return 0;
}
因篇幅问题不能全部显示,请点此查看更多更全内容