'pow'在此范围内未声明 [英] 'pow' Was Not Declared In This Scope

查看:1591
本文介绍了'pow'在此范围内未声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>
#include <string.h>

using namespace std;

int main()
{
    int e=0;
    int b=0;
    cout<<"Enter Exponent";
    cin>>e;
    cout<<"Enter Base";
    cin>>b;
    pow(e, b);
    cout<<"Power:"<<e;
    return 0;
}

void pow(int e, int b)
{
  int t=1;
  while(b==t)
  {
    e=e*b;
    t++;
  }
}




ulaga.cpp | 29 |错误:'pow'未在此范围内声明

ulaga.cpp|29|error: 'pow' was not declared in this scope

任何人都可以解释为什么会发生此错误?

Can any one explain why this error occurred?

推荐答案

C ++编译器按顺序顺序解析代码文件。即线1,然后是线2,然后是线3 ...等等。因此,当编译器到达 中的函数调用语句 pow(e,b); 函数,它还没有达到函数的定义 void pow(int e,int b) 下的 main() 有两种方法来解决这个问题。

The C++ compiler parses through your code file sequentially in order. i.e. line 1 then line 2 then line 3... and so on. So by the time the compiler comes to the function call statement pow(e, b); in your main() function, it hasn't yet reached the definition of the function void pow(int e, int b) below the main() function and therefore gives you the error. There are two ways to solve this.

1)移动 的定义void pow(int e,int b) (和您计划从 main()调用的任何其他函数) 函数本身。这样,编译器已经解析并且在到达 pow(e,b); main()

1) Move the definition of void pow(int e, int b) (and any other function that you plan to call from main()) above the main() function itself. This way the compiler has already parsed and is aware of your function before it reaches the pow(e, b); line in your main().

2)另一种方法是使用forward声明。这意味着在 main()之前添加 void pow(int e,int b); 函数。这告诉编译器,正向声明(在这种情况下 void pow(int e,int b) 代码文件,但可以在文件中的函数的定义代码之前调用。这是一个更好的方法,因为您的文件中可能有多个函数以不同顺序调用另一个函数,并且在文件中调用它们之前,可能不容易重新排列它们的定义。以下是关于转发声明的精彩阅读

2) The other way is to use a forward declaration. This means adding the line void pow(int e, int b); before the main() function. This tells the compiler that the function given by the forward declaration (in this case void pow(int e, int b)) is defined in this code file but may be called before the definition code of the function in the file. This is a better method as you may have multiple functions in your file calling one another in different order and it may not be easy to rearrange their definitions to appear before they are called in a file. Here's a good read on Forward Declaration

您可能还需要通过引用您的函数来传递参数,以获得正确的结果。即使用 void pow(int& e,int& b) 。这将导致在 pow() 函数中修改的值实际应用于整数 e c> strong>执行。有关通过引用在函数中传递参数的链接非常适合解释此问题。

You may also want to pass parameters by reference to your function to get the correct result. i.e. use void pow(int& e, int& b). This will cause the values modified in your pow() function to actually be applied to integers e and b and not just to their copies which will be thrown away after pow() is done executing. This link about passing arguments by reference in functions is pretty good at explaining this.

这篇关于'pow'在此范围内未声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆