2012-07-03 55 views
0

这是一个非常简单的程序。我在顶部和循环中定义了一个函数,我正在调用函数print为什么这个循环不起作用?

但我收到以下错误:

prog.cpp:5: error: variable or field ‘print’ declared void 
prog.cpp:5: error: ‘a’ was not declared in this scope 
prog.cpp: In function ‘int main()’: 
prog.cpp:11: error: ‘print’ was not declared in this scope 

这就是:

#include <iostream>  
using namespace std; 

void print(a) { 
    cout << a << endl; 
} 

int main() { 
    for (int i = 1; i <= 50; i++) { 
     if (i % 2 == 0) print(i); 
    } 

    return 0; 
} 
+3

“一” 中的函数参数的类型? – phantasmagoria

+1

[这套好的C++教程](http://www.cplusplus.com/doc/tutorial/)可能会对你有所帮助。 – Gigi

+3

为什么这么多downvotes? OP提供最少的工作示例,并且错误消息已完成。 –

回答

8

您定义print时忘了申报类型的a

6

试试这个:

void print(int a) { 
0

变化:

void print(int a) { // notice the int 
    cout << a << endl; 
} 
2

C++没有按具有动态类型。所以您需要手动指定类型的“a”变量或使用函数模板。

void print(int a) { 
    cout << a << endl; 
} 

template <typename T> 
void print(T a) { 
    cout << a << endl; 
} 
0
#include <iostream> 

using namespace std; 

void print(int a) { 
    cout << a << endl; 
} 

int main() { 
    for (int i = 1; i <= 50; i++) { 
     if (i % 2 == 0) print(i); 
    } 

    return 0; 
}