- 運算符重載
- 函數(shù)重載
重載聲明是指一個與之前已經(jīng)在該作用域內(nèi)聲明過的函數(shù)或方法具有相同名稱的聲明呀潭,但是它們的參數(shù)列表和定義(實現(xiàn))不相同。
1.函數(shù)重載
注意:同名函數(shù)的形式參數(shù)(指參數(shù)的個數(shù)出皇、類型或者順序)必須不同,返回類型的不同不能區(qū)分重載函數(shù)哗戈。
#include <iostream>
using namespace std;
class printData {
public:
// 同名函數(shù) print() 被用于輸出不同的數(shù)據(jù)類型
void print(int i) {
cout << "Printing int: " << i << endl;
}
void print(double f) {
cout << "Printing float: " << f << endl;
}
void print(char *c) {
cout << "Printing character: " << c << endl;
}
};
int main() {
printData pd;
pd.print(5); // Call print to print integer
pd.print(500.263); // Call print to print float
pd.print("Hello C++"); // Call print to print character
return 0;
}
Printing int: 5
Printing float: 500.263
Printing character: Hello C++
2.運算符重載
#include <iostream>
using namespace std;
class Distance {
private:
int feet; // 0 到無窮
int inches; // 0 到 12
public:
Distance() { // 默認構(gòu)造函數(shù)
feet = 0;
inches = 0;
}
Distance(int f, int i) { // 自定義初值構(gòu)造函數(shù)
feet = f;
inches = i;
}
// 顯示距離的方法
void displayDistance() {
cout << "F: " << feet << " I:" << inches << endl;
}
// 重載負運算符( - )
Distance operator-() {
feet = -feet;
inches = -inches;
return Distance(feet, inches);
}
};
int main() {
Distance D1(11, 10), D2(-5, 11);
-D1; // 取相反數(shù)
D1.displayDistance(); // 距離 D1
-D2; // 取相反數(shù)
D2.displayDistance(); // 距離 D2
return 0;
}
F: -11 I:-10
F: 5 I:-11
#include <iostream>
using namespace std;
class Distance {
private:
int feet; // 0 到無窮
int inches; // 0 到 12
public:
// 所需的構(gòu)造函數(shù)
Distance() {
feet = 0;
inches = 0;
}
Distance(int f, int i) {
feet = f;
inches = i;
}
// 把運算符重載函數(shù)聲明為類的友元函數(shù)郊艘,這樣就能不用創(chuàng)建對象而直接調(diào)用函數(shù)
friend istream &operator>>(istream &input, Distance &D) { // 輸入流,必須是&
input >> D.feet >> D.inches;
return input;
}
friend ostream &operator<<(ostream &output, const Distance &D) {
output << "F : " << D.feet << " I : " << D.inches;
return output;
}
};
int main() {
Distance D;
cout << "Enter the value of object : " << endl;
cin >> D;
cout << "Distance :" << D << endl;
int a;
cout << "輸入個int" << endl; // 原本的輸入輸出流依然可以用
cin >> a;
cout << a << endl;
return 0;
}
Enter the value of object :
23 1
Distance :F : 23 I : 1
輸入個int
12
12