一、重载为类的成员函数
重载单目运算符“++”,如果重载的是前置运算符“++”,则++a1的调用相当于调用函数a1.operator++()。如果重载的是后置运算符“++”,则运算符重载函数需要带一个整型参数,即“operator++(int)”,参数int仅仅表示后置运算,用于和前置运算区分,并无其他意义。为了加深读者的理解,下面通过案例演示前置运算符“++”与后置运算符“++”的重载,如例所示。
#include <iostream>
using namespace std;
class A
{
private:
int _x;
int _y;
public:
A(int x, int y) :_x(x), _y(y) {}
void show1() const;
A operator++(); //重载前置++
A operator++(int); //重载后置++
};
void A::show1() const
{
cout << "(_x,_y)=" << "(" << _x << "," << _y << ")" << endl;
}
A A::operator++()
{
++_x;
++_y;
return *this;
}
A A::operator++(int)
{
A a = *this;
++(*this);
return a;
}
int main()
{
A a1(1, 2), a2(3, 4);
(a1++).show1();
(++a2).show1();
}
*表示的解引用,那么*this
就很好理解了,就是指针的内容,即对象本身。
那他的用途是在哪呢?
int getData()
{
return (*this).data;
//return this->data; 作用一致
}
A setData(int s)
{
this->data = s;
return *this;
}
void printData()
{
printf("data = %d",this->data);
}
int main()
{
A a(20);
a.setData(10).printData();
}
这样我们可以把设置data值和打印函数放在同一条序列上了。
二、重载为类的友元函数
重载为类的友元函数时,由于没有隐含的this指针,因此操作数的个数没有变化,所有的操作数都必须通过函数的参数进行传递,函数的参数与操作数自左至右保持一致。下面通过案例演示将运算符“+”和“?”重载为类的友元函数,如例所示。
#include <iostream>
using namespace std;
class A
{
private:
int _x;
int _y;
public:
A(int x = 0, int y = 0) :_x(x), _y(y) {}
void showMsg() const;
friend A operator+(const A& a1, const A& a2);
friend A operator-(const A& a1, const A& a2);
};
void A::showMsg() const
{
cout << "(_x,_y)=" << "(" << _x << "," << _y << ")" << endl;
}
A operator+(const A& a1, const A& a2)
{
return A(a1._x + a2._x,a1._y+a2._y);
}
A operator-(const A& a1, const A& a2)
{
return A(a1._x-a2._x,a1._y-a2._y);
}
int main()
{
A a1(1, 2);
A a2(4, 5);
A a;
cout << "a1: ";
a1.showMsg();
cout << "a2: ";
a2.showMsg();
cout << "a: ";
a = a1 + a2;
a.showMsg();
cout << "a: ";
a = a1 - a2;
a.showMsg();
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。