【C++深度剖析學習總結】 30 操作符重載
作者 CodeAllen ,轉載請註明出處
爲了解決複數直接操作的問題,使用操作符重載實驗
驗證下下方的方案是否可行?
實驗1:複數的加法操作
#include <stdio.h>
class Complex
{
int a;//hide variable
int b;
public:
Complex(int a = 0, int b = 0)
{
this->a = a;
this->b = b;
}
int getA()
{
return a;
}
int getB()
{
return b;
}
friend Complex Add(const Complex& p1, const Complex& p2);
};
Complex Add(const Complex& p1, const Complex& p2)
{
Complex ret;
ret.a = p1.a + p2.a;
ret.b = p1.b + p2.b;
return ret;
}
int main()
{
Complex c1(1, 2);
Complex c2(3, 4);
Complex c3 = Add(c1, c2); // c1 + c2
printf("c3.a = %d, c3.b = %d\n", c3.getA(), c3.getB());
return 0;
}
2.思考
Add函數可以解決Complex對象相加的問題,但是Complex是現實世界中確實存在的複數,並且複數在數學中的地位和普通的實數相同。
爲什麼不讓+操作符也支持複數相加呢?
3.操作符重載
C++中的重載能夠擴展操作符的功能
操作符的重載以函數的方式進行
本質:
用特殊形式的函數擴展操作符的功能
通過operator關鍵字可以定義特殊的函數
operator的本質是通過函數重載操作符
operator語法:
Sign爲系統中預定義的操作符,如:+,-,*,/,等
實驗2:操作符重載–全局函數版本的實現
#include <stdio.h>
class Complex
{
int a;
int b;
public:
Complex(int a = 0, int b = 0)
{
this->a = a;
this->b = b;
}
int getA()
{
return a;
}
int getB()
{
return b;
}
friend Complex operator + (const Complex& p1, const Complex& p2);//友元函數
};//類定義之後又;
Complex operator + (const Complex& p1, const Complex& p2)
{
Complex ret;
ret.a = p1.a + p2.a;
ret.b = p1.b + p2.b;
return ret;
}
int main()
{
Complex c1(1, 2);
Complex c2(3, 4);
Complex c3 = c1 + c2; // operator + (c1, c2)
printf("c3.a = %d, c3.b = %d\n", c3.getA(), c3.getB());
return 0;
}
可以將操作符重載函數定義爲類的成員函數
- 比全局操作符重載函數少一個參數(左操作數)this充當左操作數
- 不需要依賴友元就可以完成操作符重載
- 編譯器優先在成員函數中尋找操作符重載函數
實驗3:成員函數重載操作符–成員函數調用
#include <stdio.h>
class Complex
{
int a;
int b;
public:
Complex(int a = 0, int b = 0)
{
this->a = a;
this->b = b;
}
int getA()
{
return a;
}
int getB()
{
return b;
}
Complex operator + (const Complex& p) //成員函數版本---優先調用
{
Complex ret;
printf("Complex operator + (const Complex& p)\n");
ret.a = this->a + p.a;
ret.b = this->b + p.b;
return ret;
}
friend Complex operator + (const Complex& p1, const Complex& p2);
};
Complex operator + (const Complex& p1, const Complex& p2) //全局函數版本
{
Complex ret;
printf("Complex operator + (const Complex& p1, const Complex& p2)\n");
ret.a = p1.a + p2.a;
ret.b = p1.b + p2.b;
return ret;
}
int main()
{
Complex c1(1, 2);
Complex c2(3, 4);
Complex c3 = c1 + c2; // c1.operator + (c2) ,通過成員函數實現
printf("c3.a = %d, c3.b = %d\n", c3.getA(), c3.getB());
return 0;
}
小結
操作符重載是C++的強大特性之一
操作符重載的本質是通過函數擴展操作符的功能
operator關鍵字是實現操作符重載的關鍵
操作符重載遵循相同的函數重載規則
全局函數和成員函數都可以實現對操作符的重載