H
hunter hou
Hello,Please look at the following code(from C++ in a nutshell) and my
questions.Thanks,***Hunter...
typedef void (*strproc)(const char*);
void print(const char* str)
{
std::cout << "const char*:" << str << '\n';
}
void print(int x)
{
std::cout << "int:" << x << '\n';
}
void print(double x)
{
std::cout << "double:" << x << '\n';
}
struct simple
{
void operator( )(int x) { print(x); } // print(int)
void operator( )(double x) { print(x); } // print(double)
};
typedef void (*intfunc)(int);
typedef void (*dblfunc)(double);
struct indirect
{
operator intfunc( ) { return print; } // print(int)
operator dblfunc( ) { return print; } // print(double)
operator strproc( ) { return print; } // print(const char*)
};
int main( )
{
simple sim;
indirect ind;
sim(42); // Prints "int:42"
sim.operator( )(42); // Prints "int:42"
sim(42.0); // Prints "double:42"//sim(X) is using
overloaded operator ()
ind(42); // Prints "int:42"
ind.operator intfunc( )(42); // Prints "int:42"
ind(42.0); // Prints "double:42"
ind("forty-two"); // Prints "const char*:forty-two"
}Question:The above conversion coperators are used to convert indirect to
intfunc, dblfunc,strproc, how does the above "ind" use coversion operators
to do overloading?and how to decide parameter type?
questions.Thanks,***Hunter...
typedef void (*strproc)(const char*);
void print(const char* str)
{
std::cout << "const char*:" << str << '\n';
}
void print(int x)
{
std::cout << "int:" << x << '\n';
}
void print(double x)
{
std::cout << "double:" << x << '\n';
}
struct simple
{
void operator( )(int x) { print(x); } // print(int)
void operator( )(double x) { print(x); } // print(double)
};
typedef void (*intfunc)(int);
typedef void (*dblfunc)(double);
struct indirect
{
operator intfunc( ) { return print; } // print(int)
operator dblfunc( ) { return print; } // print(double)
operator strproc( ) { return print; } // print(const char*)
};
int main( )
{
simple sim;
indirect ind;
sim(42); // Prints "int:42"
sim.operator( )(42); // Prints "int:42"
sim(42.0); // Prints "double:42"//sim(X) is using
overloaded operator ()
ind(42); // Prints "int:42"
ind.operator intfunc( )(42); // Prints "int:42"
ind(42.0); // Prints "double:42"
ind("forty-two"); // Prints "const char*:forty-two"
}Question:The above conversion coperators are used to convert indirect to
intfunc, dblfunc,strproc, how does the above "ind" use coversion operators
to do overloading?and how to decide parameter type?