在范围内声明时出错

Error declaring in scope

本文关键字:出错 声明 范围内      更新时间:2023-10-16

我在完成我的入门编码课的一项作业时遇到一些麻烦。 我在编译时不断收到错误,"[错误] '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;
}

> 在函数 main 中,你调用函数 displayBills ,但编译器此时不知道这个函数(因为它是在文件后面声明/定义的(。

要么把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通常是危险的,因为意外的名称冲突,函数应该有一个显式的返回类型(或者应该void(,...

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

就像其他人一直在说的那样,将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 文件即可。 然后在主函数上方包含您的头文件。

我会这样做,因为它可以更轻松地知道哪些功能在您的项目中的位置,而不是将所有功能都塞进 main。