C++ 允許同一作用域內對函式與運算子指定多重定義,分別稱為函式多載與運算子多載。編譯器根據引數型別進行多載決議選擇最合適版本。
同名函式參數個數、型別、順序至少一項不同(不可僅靠回傳型別區分)。
class printData {
public:
void print(int i) { cout << "int: " << i << endl; }
void print(double f) { cout << "float: " << f << endl; }
void print(char* c) { cout << "char: " << c << endl; }
};
// 呼叫:pd.print(5); pd.print(500.263); pd.print("Hello");
重新定義內建運算子行為,函式名稱格式:operator<符號>。可定義為成員函式或非成員函式。
class Box {
public:
Box operator+(const Box& b) {
Box box;
box.length = this->length + b.length;
box.breadth = this->breadth + b.breadth;
box.height = this->height + b.height;
return box;
}
};
Box3 = Box1 + Box2; // 呼叫 Box1.operator+(Box2)
Box operator+(const Box& a, const Box& b) { ... }
#include <iostream>
using namespace std;
class Box {
public:
double getVolume() { return length * breadth * height; }
void setLength(double l) { length = l; }
void setBreadth(double b) { breadth = b; }
void setHeight(double h) { height = h; }
Box operator+(const Box& b) { // 成員函式多載 +
Box box;
box.length = this->length + b.length;
box.breadth = this->breadth + b.breadth;
box.height = this->height + b.height;
return box;
}
private:
double length, breadth, height;
};
int main() {
Box Box1, Box2, Box3;
Box1.setLength(6); Box1.setBreadth(7); Box1.setHeight(5);
Box2.setLength(12); Box2.setBreadth(13); Box2.setHeight(10);
cout << "Box1: " << Box1.getVolume() << endl; // 210
cout << "Box2: " << Box2.getVolume() << endl; // 1560
Box3 = Box1 + Box2;
cout << "Box3: " << Box3.getVolume() << endl; // 5400
return 0;
}
| 可多載 | 不可多載 |
|---|---|
+ - * / % ^ & | ~ ! , = < > <= >= ++ -- << >> == != && || += -= *= %= ^= &= |= <<= >>= [] () -> ->* new new[] delete delete[] |
:: .* . ?: |
++ -- + - ! ~)+ - * / % = < > == !=)== != < > <= >=)<< >>)++ -- 前綴/後綴區分= += -=)()[]->