运算符重载:为自己的类重载运算符
注:. ?: 。。。。。。等等有些不能重载
示例类如下:
#include<iostream>
using namespace std;
class person
{
public:
int m_age;
};
int main()
{
return 0;
}
重载:operator+运算符
重载+:
int operator+(person p)
{
return this->m_age + p.m_age;
}
重载-
int operator-(person p)
{
return this->m_age - p.m_age;
}
重载*
int operator*(person p)
{
return this->m_age * p.m_age;
}
重载/
int operator/(person p)
{
return this->m_age / p.m_age;
}
重载<
bool operator<(person p)
{
return this->m_age < p.m_age;
}
重载>
bool operator>(person p)
{
return this->m_age > p.m_age;
}
重载=
bool operator=(person p)
{
if (this->m_age == p.m_age) return true;
return false;
}
重载()
void operator()()
{
cout << "重载()";
}
重载!=
bool operator!=(person p)
{
if (this->m_age == p.m_age) return false;
return true;
}
重载[]
int operator[](int a)
{
return arr[a];
}
重载<<
friend ostream& operator<<(ostream& o,person p)
{
o << p.m_age;
return o;
}
重载>>
friend istream& operator>>(istream& i,person& p)
{
i >> p.m_age;
return i;
}
重载->
int operator->()
{
return *m_age;
}
运算符重载的本质是函数调用!!!
运算符重载的本质是函数调用!!!
运算符重载的本质是函数调用!!!
欢迎补充