C++ Tutorial/Function/function overload with cast — различия между версиями
Admin (обсуждение | вклад) м (1 версия: Импорт контента...) |
|
(нет различий)
|
Текущая версия на 10:29, 25 мая 2010
Automatic type conversions can affect overloaded function resolution
#include <iostream>
using namespace std;
void f(int x);
void f(double x);
int main() {
int i = 1;
double d = 1.1;
short s = 9;
float r = 1.5F;
f(i); // calls f(int)
f(d); // calls f(double)
f(s); // calls f(int) -- type conversion
f(r); // calls f(double) -- type conversion
return 0;
}
void f(int x) {
cout << "Inside f(int): " << x << "\n";
}
void f(double x) {
cout << "Inside f(double): " << x << "\n";
}
Inside f(int): 1 Inside f(double): 1.1 Inside f(int): 9 Inside f(double): 1.5
Define overload function with short integer parameter
#include <iostream>
using namespace std;
void f(int x);
void f(short x);
void f(double x);
int main() {
int i = 1;
double d = 1.1;
short s = 9;
float r = 1.5F;
f(i); // calls f(int)
f(d); // calls f(double)
f(s); // now calls f(short)
f(r); // calls f(double) -- type conversion
return 0;
}
void f(int x) {
cout << "Inside f(int): " << x << "\n";
}
void f(short x) {
cout << "Inside f(short): " << x << "\n";
}
void f(double x) {
cout << "Inside f(double): " << x << "\n";
}
Inside f(int): 1 Inside f(double): 1.1 Inside f(short): 9 Inside f(double): 1.5