C++:对一些函数感到困惑

C++ : Confused on something about functions

本文关键字:函数 C++      更新时间:2023-10-16
#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: " << y << "n";
    return 0;
}
int myFunc (unsigned short int x )
{
    return (4 * x );
}

现在这个^代码有效,但当我更改时

y = myFunc(x);

进入

y = myFunc(int);

它将不再工作,为什么?

y =myFunc(int);

这不是一个有效的表达式。int是一个类型,不能将类型作为参数传递给函数。

if
x=7

y=myFunc(x(等于y=myFunc(7(;

如果使用int,它的值是多少?因此错误发生

因为int是一个保留字。即使不是,您也没有声明(并定义(名为"int"的标识符。

这是因为编译器需要类型为unsigned short int的值,但您传递了一个类型为int。你期望得到什么?4*int的结果未定义。

使用模板时可以传递类型。查看以下示例:

// 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