在范围内声明时出错
Error declaring in scope
我在完成我的入门编码课的一项作业时遇到一些麻烦。 我在编译时不断收到错误,"[错误] '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。
相关文章:
- GLUT 问题:重新声明 c++ 内置类型'wchar_t'时出错
- 缺少类型说明符 - int 假定 声明静态成员后出错
- 为什么在定义类之前声明类的对象会在友元类中给出错误,而在友元函数中不会出错
- 在 mingw64- 变量下的窗口中编译 openvpn3 时出错,未在范围内声明
- 在循环中重新声明 for 循环变量时出错
- 声明数组>> int arr[] 时出错;在C++(虽然在 Java 中有效)?
- 使用输出在声明容差范围内的EXPECT_NEAR时出错
- GNU 链接器:如果头文件中的指针被声明为 NULL 和/或 extern,则出错
- 在同一命名空间中声明变量和函数是否出错?[C++]
- 在范围内声明时出错
- 在声明类类型的QVector时出错
- "Undefined reference to"使用双模板类声明对象时出错
- 编译向导生成的MFC应用程序时出错;缺少CDocument声明
- 当从c切换到c++时,c++中带有双指针的函数声明和定义会出错
- 尝试在头文件上私下声明向量时出错
- 声明类类型变量时出错
- 'Incomplete type' 为标准::函数声明指向成员的指针函数模板参数时出错
- C++出错:尚未声明object_var
- 编译时类中未声明任何成员函数时出错
- LNK2005在.hpp文件中声明函数时出错