【问题标题】:Why does this loop not work?为什么这个循环不起作用?
【发布时间】:2012-07-03 13:34:43
【问题描述】:

这是一个非常简单的程序。我在顶部定义了一个函数,在循环中我调用了函数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;
}

【问题讨论】:

  • 函数参数中“a”的类型?
  • This good set of c++ tutorials 可以帮到你。
  • 为什么有这么多反对票? OP 提供了一个最小的工作示例,并且错误消息是完整的。
  • @Gigi 我正在阅读它,它真的很棒。谢谢!

标签: c++ for-loop


【解决方案1】:

定义print时忘记声明a的类型。

【讨论】:

    【解决方案2】:

    试试这个:

    void print( int a ) {
    

    【讨论】:

      【解决方案3】:

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

      void print( int a ) {
          cout << a << endl;
      }
      
      template <typename T>
      void print( T a ) {
          cout << a << endl;
      }
      

      【讨论】:

        【解决方案4】:

        改为:

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

        【讨论】:

          【解决方案5】:
          #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;
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2013-12-13
            • 2010-10-29
            • 1970-01-01
            • 1970-01-01
            • 2019-11-21
            • 2011-12-21
            相关资源
            最近更新 更多