C++ 中的函式過載和返回型別
在同一作用域內,可以對同一函式名使用多個定義。函式的定義必須透過引數列表中的型別和/或引數的數量而有所不同。你不能過載僅因返回型別不同而不同的函式宣告。
函式過載基本上是編譯時多型。它檢查函式簽名。如果簽名不相同,則它們可以被過載。函式的返回型別不會對函式過載產生任何影響。返回型別不同的同函式簽名不會被過載。
以下是使用同一函式 print() 來列印不同資料型別的示例
示例程式碼
#include <iostream> using namespace std; class printData { public: 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(void) { 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++
廣告