重载: 实现函数对应的载入。
运算符重载:实现类的一些操作,类不能实现自增自减,类可以理解成一个数据类型。
实现类的重载的方法:友元函数实现,以及类内声明和类外实现(学完STL再补充)
友元函数实现运算符的重载(跟函数声明类似)
五个特殊运算符的重载: =,++,--,<<,>>的重载
PS:运算符重载很重要跟后面学STL很有关联,每个运算符都很重要
#include<iostream>
using namespace std;
class Will
{
int m_clo;
int m_ll;
public:
Will(int a,int b)
{
m_clo = a;
m_ll = b;
}
Will():m_clo(0),m_ll(0) //无参构造也要整一个啊!!!!
{}
Will operator +(const Will &r1)const;//+运算符的重载
friend void show(const Will& a);
Will operator *(const Will &r2)const;//*运算符的重载
bool operator <(const Will &r3)const;//<运算符的重载
bool operator ==(const Will &r4)const;// ==运算符的重载
friend Will operator -(const Will &r5,const Will &r6);
};
Will operator -(const Will &r5,const Will &r6)
{
Will one ;
one.m_clo = r5.m_clo - r6.m_clo;
one.m_ll = r5.m_ll - r6.m_ll;
return one;
}
void show(const Will& a)
{
cout<<a.m_clo<<" "<<a.m_ll<<endl;
}
Will Will::operator +(const Will &r1)const
{
Will one;
one.m_clo = this->m_clo+r1.m_clo;
one.m_ll = this->m_ll + r1.m_ll;
return one;
}
Will Will::operator *(const Will &r2)const
{
Will one;
one.m_clo = m_clo * r2.m_clo;
one.m_ll = m_ll* r2.m_ll;
return one;
}
bool Will::operator <(const Will &r3)const
{
return this->m_ll*r3.m_clo < this->m_clo* r3.m_ll;
}
bool Will::operator ==(const Will &r4)const
{
return this->m_clo==r4.m_clo&&this->m_ll == r4.m_ll;
}
int main()
{
Will r1(3,4);
Will r2(3,4);
Will r3;
cout<<"实现+"<<endl;
r3 = r1+ r2;
show(r3);
cout<<"实现*"<<endl;
Will r4;
r4 = r1*r2;
show(r4);
cout<<"实现<"<<endl;
cout<<(r1 < r2 ?"true":"false")<<endl;
cout<<"实现=="<<endl;
cout<<(r1 == r2 ? "true":"false")<<endl;
cout<<"实现-"<<endl;
Will r5;
r5 = r1 - r2;
show(r5);
return 0;
}