同一作用域內,函數名相同但參數列表不同(類型、個數、順序),即構成重載。返回類型不參與重載區分。
void func(int a) { cout << "int: " << a << endl; }
void func(float a) { cout << "float: " << a << endl; }
void func(double a) { cout << "double: " << a << endl; }
int main() {
func(4); // 調用 int 版本
func(3.1f); // 調用 float 版本
func(3.14); // 調用 double 版本
}
class Cube {
int x, y;
public:
void sum() { cout << x^3 << ' ' << y^3; }
void sum(int a, int b) { x=a; y=b; cout << x << ' ' << y; }
};
int main() {
Cube c;
c.sum(2,3); // 設置並輸出 2 3
c.sum(); // 輸出立方 8 27
}
class Rectangle {
int len, wid, hgt;
public:
Rectangle() { cout << "構造矩形\n"; }
Rectangle(int l, int w) : len(l), wid(w) { cout << "面積: " << l*w; }
Rectangle(int l, int w, int h) : len(l), wid(w), hgt(h) { cout << "體積: " << l*w*h; }
};
int main() {
Rectangle a; // 默認
Rectangle b(3,4); // 面積 12
Rectangle c(3,4,5); // 體積 60
}
this 指針隱式參數,但重載規則同普通函數func(int) 和 func(float) 調用 func(3.14) 會報錯(double 無精確匹配)函數重載提高代碼可讀性,減少命名負擔,是 C++ 多態性的靜態體現(編譯時綁定)。