在范围内声明错误

Error declaring in scope

我在完成我的入门编码任务之一时遇到了一些困难 class。我在编译时不断收到错误消息,“[Error] 'displayBills' 未在此范围内声明。我将附上我的代码,任何建议将不胜感激,谢谢!

#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int dollars;
cout << "Please enter the whole dollar amount (no cents!).  Input 0 to terminate: ";
cin >> dollars;
while (dollars != 0)
    {
    displayBills(dollars);
    cout << "Please enter the a whole dollar amount (no cents!).  Input 0 to terminate: ";
    cin >> dollars;
    }
return 0;
}

displayBills(int dollars)
{
int ones;
int fives;
int tens;
int twenties;
int temp;

twenties = dollars / 20;
temp = dollars % 20;
tens = temp / 10;
temp = temp % 10;
fives = temp / 5;
ones = temp % 5;

cout << "The dollar amount of ", dollars, " can be represented by the following monetary denominations";
cout << "     Twenties: " << twenties;
cout << "     Tens: " << tens;
cout << "     Fives: " << fives;
cout << "     Ones: " << ones;
}

您没有为 displayBills 函数指定前向声明。您必须指定一个或将您的函数放在对它的任何调用之前。

在函数main中,你调用了函数displayBills,但此时编译器还不知道这个函数(因为它在文件后面declared/defined)。

要么将 displayBills(int dollars) { ... 的定义放在函数 main 之前,要么至少将此函数的前向声明放在函数 main:

之前
displayBills(int dollars);  // Forward declaration; implementation may follow later on;
// Tells the compiler, that function `displayBills` takes one argument of type `int`.
// Now the compiler can check if calls to function `displayBills` have the correct number/type of arguments.

int main() {
   displayBills(dollars);  // use of function; signature is now "known" by the compiler
}

displayBills(int dollars) {  // definition / implementation
  ...
}

顺便说一句:您的代码中有几个问题您应该注意,例如using namespace std 通常是危险的,因为意外的名称冲突,函数应该有一个明确的 return 类型(或者应该是 void),...

就像其他人所说的那样,将 displayBills 放在 main 之上将有助于解决您的问题。但也在名为 displayBills.h 和

的头文件中声明 displayBills
#ifndef DISPLAYBILLS_H_INCLUDED
#define DISPLAYBILLS_H_INCLUDED

displayBills(int dollars);
#endif DISPLAYBILLS_H_INCLUDED

然后您可以获得 displayBills.cpp 的 cpp 文件,您将在其中定义函数 displayBills(不要忘记包含 displayBills.h)

 #include "displayBills.h"

然后将它从您的主要功能下移动到它自己的 cpp 文件中。然后在你的主要功能之上包括你的头文件。

我会这样做,因为这样可以更轻松地了解项目中的哪些函数,而不是将所有函数都塞进主函数中。