文章概述
- 定义运算符重载的步骤
- 使用成员函数和友元函数重载二元运算符
- 使用成员函数和友元函数重载一元运算符
上一篇,我们已经熟悉重载运算符的理论知识,这篇主要是实际操作(代码)。
定义运算符重载的步骤
a.我们首先要知道根据操作数的个数将运算符分为一元运算符和二元运算符。
b.定义运算符重载的步骤:
- 明白运算符重载是一个函数,写出函数名称。(函数名称: operator+运算符(+ - [] = 等))
- 根据操作数和其类型,确定函数参数
- 根据业务,完善函数的返回值(函数的返回值是引用,对象,指针)实现函数业务
使用成员函数和友元函数重载二元运算符
a. 使用友元函数完成二元运算符重载:
函数返回值 operator op (object& A,object& B);
b. 使用成员函数完成二元运算符重载:
函数返回值 类名::operator op(object& B);
c.我们以+ - 运算符为例:
class Test
{
friend Test operator+ (Test& a, Test& b);
private:
int x;
int y;
public:
Test()
{
this->x = 2;
this->y = 3;
}
Test(int x,int y)
{
this->x = x;
this->y = y;
}
//输出
void printF()
{
cout << this->x << endl;
cout << this->y << endl;
}
//使用成员函数实现-号运算符重载
Test operator- (Test& b)
{
Test c(this->x-b.x,this->y-b.y);
return c;
}
};
//使用友元函数实现+号运算符重载
Test operator+ (Test& a, Test& b)
{
Test c(a.x+b.y,a.y+b.y);
return c; //返回的是一个匿名对象
}
int main()
{
//实现的需求: c =a+b
//确定友元函数的声明: Test operator+ (Test& a,Test& b);
Test a(4,5);
Test b(2,1);
//实现机制: 首先C++编译器看到opretor+会知道我们重载了+号运算符。
//程序执行到Test c = a + b; 会根据a+b找到符合这个类型的函数
//如果我们写了,C++编译器可以直接调用。(可以断点自己调试代码)
Test c = a + b;
c.printF();
Test d = a - b;
d.printF();
return 0;
}
使用成员函数和友元函数重载一元运算符
一元运算符: ++a,a++,–a,a–。前置就是先执行运算之后使用。后置就是先使用之后执行运算。
a. 使用成员函数重载一元运算符:
//操作数由this指针隐式传递
函数返回类型 operator op();
b. 使用友元函数重载一元运算符:
函数返回类型 operator op(object& b);
c. 我们以++a,a++,–a,a–为例
class Test
{
friend Test& operator++(Test& a);
friend Test operator++(Test&a, int);
private:
int x;
public:
Test()
{
x = 0;
}
int getX() { return x; }
//使用成员运算符实现重载前置--运算符
Test& operator--()
{
this->x--;
return *this;
}
//使用成员函数实现运算符重载后置++运算符
Test operator--(int)
{
Test temp = *this;
this->x--;
return temp;
}
};
//使用友元函数重载前置++运算符
Test& operator++(Test& a)
{
a.x++;
return a;
}
//使用友元函数重载后置++运算符
//不要返回一个临时对象的引用
Test operator++(Test&a,int)
{
Test temp = a;
a.x++;
return temp;
}
int main()
{
//实现的需求: ++a;
Test a;
//++a; Test operator++(Test& a)
++a;
cout << a.getX() << endl;
--a;
cout << a.getX() << endl;
Test b;
//实现的需求: a++ 先使用a再++
Test c=b++;
cout << c.getX() << endl;
cout << b.getX() << endl;
//
Test d;
d--;
cout << d.getX() << endl;
return 0;
}