Example:
void f(int i)
{
printf("i = %d\n\n", i);
}
void f(double f)
{
printf("f = %f\n\n", f);
}
|
C++ uses function name and number and type of the actual parameters to determine the intended function....
int i; double f; f(i); // will invoke f(int) f(f); // will invoke f(double) |
void f(float f)
{
cout << "f = " << f << endl << endl;
}
void f(double d)
{
cout << "d = " << d << endl << endl;
}
int main(int argc, char *argv[])
{
f(4.0); // Which f ???
}
|
We will see an example below.
We have seen that C++ treats integer multiplication and float multiplication differently - due to the different internal encoding.
class Matrix3
{
public:
float A[3][3];
};
class Vector3
{
public:
float x[3];
};
|
// ============================ Matrix-matrix multiply
Matrix3 operator*(Matrix3 & M1, Matrix3 & M2)
{
Matrix3 r;
int i, j, k;
for (i = 0; i < 3; i=i+1)
for (j = 0; j < 3; j=j+1)
r.A[i][j] = 0;
for (i = 0; i < 3; i=i+1)
for (j = 0; j < 3; j=j+1)
for (k = 0; k < 3; k=k+1)
r.A[i][j] = r.A[i][j] + M1.A[i][k]*M2.A[k][j];
return r;
}
// ============================ Matrix-vector multiply
Vector3 operator*(Matrix3 &M, Vector3 &v)
{
Vector3 z;
int i, j;
for (i = 0; i < 3; i=i+1)
z.x[i] = 0;
for (i = 0; i < 3; i=i+1)
for (j = 0; j < 3; j=j+1)
z.x[i] = z.x[i] + M.A[i][j]*v.x[j];
return z;
}
|
int main(int argc, char *argv[])
{
Matrix3 M1, M2, M3;
Vector3 v1, v2;
M3 = M1 * M2; // Selects Matrix-matrix multiply
// because operator*(Matrix3,Matrix3)
v2 = M2 * v1; // Select Matrix-vector multiply
// because operator*(Matrix3,Vector3)
}
|