操作符重載
- C++中的重載能夠擴展操作符的功能
- 操作符的重載以函數的方式進行
- 本質:
- 用特殊形式的函數擴展操作符的功能
- 使用:
- 通過
operator
關鍵字可以定義特殊的函數 operator
的本質是通過函數重載操作符- 語法:
- 通過
Type operator Sign(const Type& p1, const Type& p2)
{
Type ret;
return ret;
}
// Sign 爲系統中預定義的操作符,如: +, -, *, /, 等
這裏舉一個例子:
#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;
}
另一種用法:
- 可以將操作符重載函數定義爲類的成員函數
- 比全局操作符重載函數少一個參數(左操作數)
- 不需要依賴友元就可以完成操作符重載
- 編譯器優先在成員函數中尋找操作符重載函數
class Type
{
public:
Type operator Sign(const Type& p)
{
Type ret;
return ret;
}
};
這裏再舉一個例子:
#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
關鍵字是實現操作符重載的關鍵- 操作符重載遵循相同的函數重載規則
- 全局函數和成員函數都可以實現對操作符的重載