十分鐘理解C ++中的運(yùn)算符重載
在C ++中,我們可以使運(yùn)算符為用戶定義的類工作。這意味著C ++能夠?yàn)檫\(yùn)算符提供數(shù)據(jù)類型的特殊含義,這種能力稱為運(yùn)算符重載。
例如,我們可以在String之類的類中重載運(yùn)算符'+',以便僅使用+就可以連接兩個(gè)字符串。 算術(shù)運(yùn)算符可能會(huì)重載的其他示例類是復(fù)數(shù),小數(shù),大整數(shù)等。
一個(gè)簡(jiǎn)單而完整的例子
- #include<iostream>
- using namespace std;
- class Complex {
- private:
- int real, imag;
- public:
- Complex(int r = 0, int i =0) {real = r; imag = i;}
- Complex operator + (Complex const &obj) {
- Complex res;
- res.real = real + obj.real;
- res.imag = imag + obj.imag;
- return res;
- }
- void print() { cout << real << " + i" << imag << endl; }
- };
- int main()
- {
- Complex c1(10, 5), c2(2, 4);
- Complex c3 = c1 + c2;
- c3.print();
- }
操作員功能和普通功能有什么區(qū)別?
操作員功能與普通功能相同。唯一的區(qū)別是,運(yùn)算符的名稱始終是運(yùn)算符關(guān)鍵字,后跟運(yùn)算符的符號(hào),并且在使用相應(yīng)的運(yùn)算符時(shí)會(huì)調(diào)用運(yùn)算符功能。
以下是全局運(yùn)算符功能的示例。
- #include<iostream>
- using namespace std;
- class Complex {
- private:
- int real, imag;
- public:
- Complex(int r = 0, int i =0) {real = r; imag = i;}
- void print() { cout << real << " + i" << imag << endl; }
- friend Complex operator + (Complex const &, Complex const &);
- };
- Complex operator + (Complex const &c1, Complex const &c2)
- {
- return Complex(c1.real + c2.real, c1.imag + c2.imag);
- }
- int main()
- {
- Complex c1(10, 5), c2(2, 4);
- Complex c3 = c1 + c2;
- c3.print();
- return 0;
- }
我們可以讓所有運(yùn)算符超負(fù)荷嗎?
除了少數(shù)操作員之外,幾乎所有操作員都可以重載。以下是不能重載的運(yùn)算符的列表。
為什么不能。(點(diǎn)),::,?:和sizeof是否過(guò)載?
請(qǐng)參閱此以獲取Stroustrup自己的答案。
關(guān)于運(yùn)算符重載的要點(diǎn)
1)為了使運(yùn)算符重載起作用,至少一個(gè)操作數(shù)必須是用戶定義的類對(duì)象。
2) 賦值運(yùn)算符:編譯器會(huì)自動(dòng)為每個(gè)類創(chuàng)建一個(gè)默認(rèn)的賦值運(yùn)算符。默認(rèn)賦值運(yùn)算符確實(shí)將右側(cè)的所有成員分配到左側(cè),并且在大多數(shù)情況下都可以正常工作(此行為與復(fù)制構(gòu)造函數(shù)相同)。請(qǐng)參閱此了解更多詳情。
3) 轉(zhuǎn)換運(yùn)算符:我們還可以編寫可用于將一種類型轉(zhuǎn)換為另一種類型的轉(zhuǎn)換運(yùn)算符。
- #include <iostream>
- using namespace std;
- class Fraction
- {
- int num, den;
- public:
- Fraction(int n, int d) { num = n; den = d; }
- operator float() const {
- return float(num) / float(den);
- }
- };
- int main() {
- Fraction f(2, 5);
- float val = f;
- cout << val;
- return 0;
- }
重載的轉(zhuǎn)換運(yùn)算符必須是成員方法。其他運(yùn)算符可以是成員方法或全局方法。
4)任何可以用單個(gè)參數(shù)調(diào)用的構(gòu)造函數(shù)都可以用作轉(zhuǎn)換構(gòu)造函數(shù),這意味著它也可以用于隱式轉(zhuǎn)換為正在構(gòu)造的類。
- #include<iostream>
- using namespace std;
- class Point
- {
- private:
- int x, y;
- public:
- Point(int i = 0, int j = 0) {
- x = i; y = j;
- }
- void print() {
- cout << endl << " x = " << x << ", y = " << y;
- }
- };
- int main() {
- Point t(20, 20);
- t.print();
- t = 30;
- t.print();
- return 0;
- }