C++/Function/Function Arguments
Содержание
A example of default arguments.
#include <iostream>
using namespace std;
void f(int a=0, int b=0)
{
cout << "a: " << a << ", b: " << b;
cout << "\n";
}
int main()
{
f();
f(10);
f(10, 99);
return 0;
}
Compute area of a rectangle using default arguments.
#include <iostream>
using namespace std;
double rect_area(double length, double width = 0)
{
if(!width)
width = length;
return length * width;
}
int main()
{
cout << "10 x 5.8 rectangle has area: ";
cout << rect_area(10.0, 5.8) << "\n";
cout << "10 x 10 square has area: ";
cout << rect_area(10.0) << "\n";
return 0;
}
Default function arguments
#include <iostream>
#include <string>
using namespace std;
int askNumber(int high, int low = 1);
int main()
{
int number = askNumber(5);
cout << "Thanks for entering: " << number << "\n\n";
number = askNumber(10, 5);
cout << "Thanks for entering: " << number << "\n\n";
return 0;
}
int askNumber(int high, int low)
{
int num;
do
{
cout << "Please enter a number" << " (" << low << " - " << high << "): ";
cin >> num;
} while (num > high || num < low);
return num;
}
Use default argument
#include <iostream>
using namespace std;
class myclass {
int x;
public:
myclass(int n = 0) {
x = n;
}
int getx() {
return x;
}
};
int main()
{
myclass o1(10); // declare with initial value
myclass o2; // declare without initializer
cout << "o1: " << o1.getx() << "\n";
cout << "o2: " << o2.getx() << "\n";
return 0;
}