目录
运算符重载也可以发生函数重载
加号运算符重载
成员函数重载+
class Person
{
private:
int a;
int b;
public:
Person operator+(Person& p)
{
Person temp;
temp.a = this->a + p.a;
temp.b = this->b + p.b;
return temp;
}
};
int main()
{
Person a, b, c;
c = a.operator+(b);//可以简化为 c = a + b;
}
全局函数重载+
class Person
{
public:
int a;
int b;
};
//Person operator+(Person& p1,Person &p2)的函数重载可以是Person operator+(Person& p1,int num) 这样就可以实现Person类对象和普通实数的相加了
Person operator+(Person& p1,Person &p2)
{
Person temp;
temp.a = p1->a + p2->a;
temp.b = p2->b + p2->b;
return temp;
}
int main()
{
Person a, b, c;
c = operator+(a,b);//可以简化为 c = a + b;
}
左移运算符重载(<<)
一般用全局函数重载左移运算符
//ostream &cout 用&的原因是取一个别名 cout对象只能由一个 只能去获取地址 不能重新创建一个 所以可以把cout改成其他的 比如out 然后以后输出就可以是 out<<p;
void operator<<(ostream &cout,Person &p)
{
cout<<"A="<<p.a<<"B="<<p.b;
}
/*但是上面的重载只能实现一个 cout<<p 不能实现 cout<<p<<p*/
/*下面这样就行了*/ // 下面函数的数据类型&也和上面使用&一样 只能获取地址 不能重新创建一个
ostream& operator<<(ostream &cout,Person &p)
{
cout<<"A="<<p.a<<"B="<<p.b;
return cout;
}
++运算符重载
++操作符只能作用于变量,而不能是一个数字
a++ 结束之后 是一个常数值 所以不能++(a++)
a+++b
一般看做(a++) + b
前置递增
class New
{
friend ostream& operator<<(ostream& cout, New ne);
public:
New()
{
a = 0;
}
/*加&的原因是 如果不使用& 则在使用++(++ne)完成第一次++ne操作之后 返回的是一个新的ne 而不是main函数里面创建的那个NEW ne了*/
New &operator++()
{
a++;
return *this;
}
private:
int a;
};
ostream& operator<< (ostream& cout,New ne)
{
cout << ne.a;
return cout;
}
int main()
{
New ne;
cout << ++ne;
//如果是New operator++() 则 cout<<++(++ne)的结果是2 但是如果执行
//++(++ne)
//cout<<ne;//结果是1 因为真正对main函数中ne有效的是第一个++ne 在完成这一步之后返回的就不再是 New ne了 而是一个新的变量 所以需要加上&来引用 保证返回的是一个ne
}
后置递增
加int参数的目的主要是方便函数重载 int代表占位参数 可以用于区分前置和后置递增 也必须写int 其他的不行
New operator++(int)
{
New temp = *this;//也因为这里是局部变量 所以不能返回引用
a++;
return temp;
}
重载函数调用运算符(())(伪函数)
因为使用起来非常类似于函数调用 所以称为伪函数
class Stu()
{
public:
void operator()(string a)
{
cout(a);
}
}
int main()
{
Stu stu;
stu("hello world");
//还可以直接通过匿名对象调用仿函数
Stu()("hello world");
}
>>输入输出运算符重载
class A
{
int val;
int id;
public:
A(int a, int b)
{
val = a;
id = b;
}
/*类内重载*/
ostream& operator<<(ostream& out)
{
cout << "类内重载:";
out << val <<","<<id << endl;
return out;
}
friend ostream& operator << (ostream& out, const A& a);
/*友元函数*/
};
ostream& operator << (ostream& out, const A& a)
{
cout << "类外友元的重载:";
out << a.val << "," << a.id << endl;
return out;
}
int main()
{
A a(3, 4);
a.operator<<(cout);
cout << a;
}
注意
运算符“=”、“[]”、“()”、“->”以及所有的类型转换运算符只能作为成员函数重载