问题
#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++;
}
}
Here is the error I received:
ulaga.cpp|29|error: 'pow' was not declared in this scope
Can any one explain why this error occurred?
回答1:
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) 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) 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
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.
回答2:
You need to forward declare the pow
function. Like -
....
void pow(int e, int b);
int main()
....
There are few things wrong here. For example e
is passed by value. So, e
in main is different from that of pow
.
pow(e, b);
cout<<"Power:"<<e; // This just prints the value taken from console
// And not the calculated power.
Either make pow
function to return a value (or) pass e
by reference.
回答3:
You need to use forward declaration of your function pow. Or just move it's definition above the main function.
回答4:
This can easily be fixed by just importing #include <cmath>
in the beginning of your code.
来源:https://stackoverflow.com/questions/11016189/pow-was-not-declared-in-this-scope