1、给予运算符新的意义,使其能够支持自定义类型的操作;
2、语法:
·<类型(返回值)>operator <运算符>(参数1)...
{
}
如:
void operator + (int n1)
{
}
3、成员运算符重载:在类中进行运算符重载;
·调用运算符的对象要算一个参数;
4、全局运算符重载:在类外进行运算符重载;
·根据参数顺序来决定运算符的操作数,第一个参数作为运算符左操作数,第二个参数作为运算符右操作数.
1、输出运算符重载:代码实现
#include <iostream>
using namespace std;
class person
{
public:
string p_name;
int p_age;
person():p_name(""),p_age(0)
{
}
person(string name,int age):p_name(name),p_age(age)
{
}
#if 1
void operator<<(person &p)
{
cout << "姓名" << p_name << endl;
cout << "年龄" << p_age << endl;
}
#endif
};
ostream &operator<<(ostream &out,const person &p)
{
out << "姓名:" << p.p_name << endl;
out << "年龄:" << p.p_age << endl;
return out;
}
void test1()
{
person p1("zhangsan",100);
cout << p1 << endl;
}
int main(int argc, char *argv[])
{
test1();
return 0;
}
结果:
2、加号运算符:代码实现
#include <iostream>
using namespace std;
class Data
{
public:
int _n1;
float _f1;
Data():_n1(0),_f1(0.0f)
{
}
Data(int n1,float f):_n1(n1),_f1(f)
{
}
Data operator+(const Data &d)
{
Data temp;
temp._n1 = this->_n1 + d._n1;
temp._f1 = this->_f1 + d._f1;
return temp;
}
Data & operator+(const int &n)
{
this->_n1 += n;
return *this;
}
Data & operator+(const double &f)
{
this->_f1 += f;
return *this;
}
void Datavalue()const
{
cout << "_n1:" << _n1 << endl;
cout << "_f1:" << _f1 << endl;
}
};
void test1()
{
Data d1(3,4.33);
Data d2(9,7.11);
d1 = d1 + d2;
d1 +45;
d2 +7.99;
d1.Datavalue();
d2.Datavalue();
}
int main(int argc, char *argv[])
{
test1();
return 0;
}
结果: