#include <iostream> #include <iomanip> using namespace std; // Function prototypes int square(int); double square(double); int main() { int userInt; double userReal; // Get an int and a double cout << "Enter an integer and a floating-point value: "; cin >> userInt >> userReal; // Display their squares cout << "Here are their squares:"; cout << fixed << showpoint << setprecision(2); cout << square(userInt) << " and " << square(userReal) << endl; return 0; } int square (int number) { return number * number; } double square(double number) { return number * number; }程式輸出結果:
Enter an integer and a floating-point value: 12 4.2
Here are their squares: 144 and 17.64
int square(int number)
double square(double number)
square(int)
square(double)
int square(int number) { return number * number; } double square (int number) //錯誤!形參列表必須不同 { return number * number; }當有類似函數使用不同數量的形參時,過載也很方便。例如,假設有一個程式包含的函數可以返回整數和。其中一個函數返回 2 個整數的和,另一個返回 3 個整數的和,還有一個返回 4 個整數的和。以下是它們的函數頭:
int sum(int num1, int num2)
int sum(int num1, int num2, int num3)
int sum(int num1, int num2, int num3, int num4)
#include <iostream> #include <iomanip> using namespace std; //Function prototypes char getChoice (); double calcWeeklyPay(int, double); double calcWeeklyPay(double); int main() { char selection; // Menu selection int worked; // Weekly hours worked double rate, // Hourly pay rate yearly; // Annual salary // Set numeric output formatting cout << fixed << showpoint << setprecision(2); //Display the menu and get a selection cout << "Do you want to calculate the weekly pay ofn"; cout << "(H) an hourly-wage employee, or n"; cout << "(S) a salaried employee? "; selection = getChoice (); // Process the menu selection switch (selection) { //Hourly employee case 'H': case 'h': cout << "How many hours were worked? "; cin >> worked; cout << "What is the hourly pay rate? "; cin >> rate; cout << "The gross weekly pay is $"; cout << calcWeeklyPay(worked, rate) << endl; break; //Salaried employee case 'S' : case 's' : cout << "What is the annual salary? "; cin >> yearly; cout << "The gross weekly pay is $"; cout << calcWeeklyPay(yearly) << endl; } return 0; } char getChoice() { char letter; // Holds user1s letter choice // Get the user's choice cin >> letter; // Validate the choice while (letter != 'H' && letter != 'h' && letter != 'S' && letter != 's') { cout << "Enter H or S:"; cin >> letter; } // Return the choice return letter; } double calcWeeklyPay(int hours, double payRate) { return hours * payRate; } double calcWeeklyPay(double annSalary) { return annSalary / 52.0; }程式輸出結果:
Do you want to calculate the weekly pay of
(H) an hourly-wage employee, or
(S) a salaried employee? H
How many hours were worked? 40
What is the hourly pay rate? 18.50
The gross weekly pay is $740.00