C++ : Confused on something about functions
#include <iostream>
using namespace std;
int myFunc (unsigned short int x );
int main ()
{
unsigned short int x, y;
x=7;
y = myFunc(x);
std::cout << "x:" << x << "y: " <开发者_如何学JAVA< y << "\n";
return 0;
}
int myFunc (unsigned short int x )
{
return (4 * x );
}
Now this ^ Code works, but when I change
y = myFunc(x);
into
y = myFunc(int);
it will no longer work, why is that?
y =myFunc(int);
This is not a valid expression. int
is a type, you cannot pass a type as an argument to a function.
if
x=7;
y = myFunc(x); is equal to y = myFunc(7);
if you use int, what value it has? so the error occurs
Because int is a reserved word. And even if it wasn't - you haven't declared (and defined) identifier called "int".
That's because the compiler expects the value of type unsigned short int
, but you've passed a type int
. What did you expected to get? The result of 4*int
is undefined.
You can pass types when you use templates. Take a look on the following sample:
// Here's a templated version of myFunc function
template<typename T>
T myFunc ( unsigned short int x )
{
return (4 * x );
}
...
y = myFunc<int>( x ); // here you can pass a type as an argument of the template,
// but at the same moment you need to pass a value as an argument of the function
精彩评论