在我们的编程使用中,我们对基本数据类型的数据例如整形,浮点, 双精度可以进行加减乘除. C++中通过class关键字可以自定义类类型的数据类型,但是默认不支持加减等运算符操作. 在编程实践中,我们可能需要类似基本数据类型的操作,比较幸运的是,C++给我们提供了运算符重载机制.
一, 运算符重载的方法
1, 通过友元函数来实现—这也是友元函数存在的最大意义
2,通过成员函数来实现
二,运算符重载的本质
不论采用上面那种运算符重载的方法,我们都需要自定义一个函数来实现重载, 函数的名字也是比较特殊 ,形式如: operator op. 当编译器检查到这些特殊的函数时候,就会触发运算符的重载,所以运算符的重载本质上是函数调用
三, 二元运算符重载的示例
下面的示例对二元运算符进行加和减的重载, 分别采用友元函数和成员函数的方式实现.代码如下:
//二元运算符重载
#include "iostream"
using namespace std;
class Complex{
public:
Complex(int a=0, int b=0){
this->a = a;
this->b = b;
}
//友元函数实现加法的运算符重载
friend Complex operator+(Complex& c1, Complex& c2);
void print(){
cout << "a = " << a << " b= "<< b << endl;
}
//成员函数实现减法的运算符重载
Complex operator-(Complex& c){
Complex cc;
cc.a = this->a - c.a;
cc.b = this->b - c.b;
return cc;
}
private:
int a;
int b;
};
Complex operator+(Complex& c1, Complex& c2){
Complex c;
c.a = c1.a+c2.a;
c.b = c1.b+c2.b;
return c;
}
//测试加法的运算符重载
void testAdd(){
cout << "--------testAdd()------------" << endl;
Complex c1(4,5);
Complex c2(6,5);
Complex c = c1+c2;
c.print();
}
//测试减法的运算符重载
void testDecrease(){
cout << "--------testDecrease()------------" << endl;
Complex c1(5,55);
Complex c2(6,5);
Complex c = c1-c2;
c.print();
}
int main(){
testAdd();
testDecrease();
return 0;
}
二,一元运算符重载
<一> 前置++ 前置–重载
两种方法分别实现前置++和前置–
代码如下:
#include "iostream"
using namespace std;
class Complex{
public:
Complex(int a=0, int b=0){
this->a = a;
this->b = b;
}
//友元函数实现前置++的运算符重载
friend Complex& operator++(Complex& c);
void print(){
cout << "a = " << a << " b= "<< b << endl;
}
//成员函数实现前置--运算符重载
Complex& operator--(){
this->a --;
this->b --;
return *this;
}
private:
int a;
int b;
};
Complex& operator++(Complex& c){
c.a++;
c.b++;
return c;
}
//测试前置++的运算符重载
void testAdd(){
cout << "--------testAdd()------------" << endl;
Complex c1(4,5);
c1++;
c1.print();
}
//测试前置--的运算符重载
void testDecrease(){
cout << "--------testDecrease()------------" << endl;
Complex c1(5,55);
c1 --;
c1.print();
}
int main(){
testAdd();
testDecrease();
return 0;
}
<二> 后置++ 后置–重载
当我们友元函数后者成员函数实现运算符重载的时候,发现函数名字会和前置的一样,这时候没法区分前置还是后置, 这时候后置的时候参数需要使用占位符进行替换
代码如下:
#include "iostream"
using namespace std;
class Complex{
public:
Complex(int a=0, int b=0){
this->a = a;
this->b = b;
}
//友元函数实现后置++的运算符重载
friend Complex operator++(Complex& c,int);
void print(){
cout << "a = " << a << " b= "<< b << endl;
}
//成员函数实现后置--的运算符重载
Complex operator--(int){
Complex temp = *this;
this->a --;
this->b --;
return temp;
}
private:
int a;
int b;
};
Complex operator++(Complex& c, int){
Complex temp = c;
c.a++;
c.b++;
return temp;
}
//测试后置++的运算符重载
void testAdd(){
cout << "--------testAdd()------------" << endl;
Complex c1(4,5);
c1++;
c1.print();
}
//测试后置--的运算符重载
void testDecrease(){
cout << "--------testDecrease()------------" << endl;
Complex c1(5,55);
c1 --;
c1.print();
}
int main(){
testAdd();
testDecrease();
return 0;
}