友元函数重载运算符
1.运算符重载:赋予运算符具有操作自定义类型数据功能
2.运算符重载的实质是函数调用
函数返回值类型 函数名(函数参数)
(1)函数返回值类型:运算完成后的值决定的
(2)函数名:operator 加上重载运算符组成函数名
(3)参数:看运算符的操作数,具体参数个数是要看你重载函数形式是什么
(4)函数体:写运算符具体想要的操作
3.友元函数重载和类成员函数重载(参数个数少一)
类成员函数重载运算符
#include <iostream>
#include <string>
using namespace std;
class A
{
public:
A(int a=0,int b=0):a(a), b(b){}
friend A operator+ (A one, A two);
void print()
{
cout << a << "\t" << b << endl;
}
bool operator>(A two)
{
if (this->a > two.a || (this->a == two.a&&this->b > two.b))
return true;
else
return false;
}
protected:
int a;
int b;
};
A operator+(A one, A two)
{
return A(one.a + two.a, one.b + two.b);
}
int main()
{
A one(2, 1);
A two(1, 0);
A three = one + two;//three=operator+(A one,A two);显示调用
three.print();
if (one > two/*one.operator>(two)*/)
{
cout << "one 大" << endl;
}
return 0;
}
特殊运算符重载
1.流运算符重载
(1)cin类型:istream类的对象
(2)cout类型:ostream类的对象
(3)流运算符 << >>
(4)必须采用友元函数形式重载
#include <iostream>
#include <string>
using namespace std;
class Boy
{
public:
Boy(string name="", int age=0) :name(name), age(age){}
friend istream& operator>>(istream& in, Boy& boy);
friend ostream& operator<<(ostream& out, Boy& boy);
protected:
string name;
int age;
};
istream& operator>>(istream& in, Boy& boy)
{
in >> boy.name>>boy.age;
return in;
}
ostream& operator<<(ostream& out, Boy& boy)
{
out << boy.name << "\t" << boy.age << endl;
return out;
}
int main()
{
string name;
cin >> name;
cout << name << endl;
Boy boy;
cin >> boy; //void operator>>(istream& in,Boy& boy);
cout << boy << endl; //void operator<<(ostream& out,Boy& boy);
cin >> name >> boy;
cout << name << "\t" << boy;
return 0;
}
2.++--运算符重载
(1)前置后置:增加无用参数int表示后置操作
3.文本重载
4.其他运算符
(1)= () -> [ ] 只能采用类的成员函数形式重载
(2)流重载采用友元方式
(3). .* ?: ::不能重载
5.类的隐式对象的转换
#include <iostream>
#include <string>
using namespace std;
class Boy
{
public:
Boy(string name, int age) :name(name), age(age){}
friend ostream& operator<<(ostream& out, Boy& boy)
{
out << boy.name << "\t" << boy.age;
return out;
}
Boy operator++(int)//后置
{
return Boy(name, age++);
}
Boy operator++()
{
return Boy(name, ++age);
}
Boy operator--(int)
{
return Boy(name, age--);
}
Boy operator--()
{
return Boy(name, --age);
}
protected:
string name;
int age;
};
int main()
{
Boy boy("name", 21);
Boy boy1 = boy++;
cout << boy1 << "\t" << boy << endl;
boy1 = ++boy;
cout << boy1 << "\t" << boy << endl;
return 0;
}