2011-06-13 73 views
1
#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); 
} 

弄得现在这^代码的工作,但是当我改变C++:在一些有关职能

y = myFunc(x); 

y = myFunc(int); 

将不再工作,这是为什么?

+3

它为什么会工作?你期望它做什么? – Andrei 2011-06-13 09:07:19

回答

1

这是因为编译器期望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 
5
y =myFunc(int); 

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

3

if
x = 7;

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

如果你使用int,它有什么值?所以发生错误

+0

计算机就像你解决你的代数方程一样执行.. :) – Jagadeesan 2011-06-13 09:08:05

2

因为int是保留字。即使它不是 - 你还没有声明(和定义)称为“int”的标识符。