c++ - 为什么我不能在声明其内容之前声明一个函数? (c++)

标签 c++ forward-declaration

我有一个添加数字的幂的程序,由于某种原因,当我运行它时,它一直向我抛出错误,如果我在 main 函数之前声明和定义内容,程序运行正常,但我不明白为什么这是必要的...这是给我带来问题的代码:

#include <iostream>
#include <math.h>
using namespace std;

long long addPow(int n, int p);

int main() {
    cout << addPow(100, 1) * addPow(100, 1) - addPow(100, 2) << endl;
    return 0;
}

addPow(int n, int p) {
    long long sum = 0;
    for (int i = 1; i <= n; i++) {
        sum += pow(i, p);
    }
    return sum;
}

将其更改为这个可以解决所有问题,但我真的不知道为什么...

#include <iostream>
#include <math.h>
using namespace std;

long long addPow(int n, int p) {
    long long sum = 0;
    for (int i = 1; i <= n; i++) {
        sum += pow(i, p);
    }
    return sum;
}

int main() {
    cout << addPow(100, 1) * addPow(100, 1) - addPow(100, 2) << endl;
    return 0;
}

如果有人能帮助我,我将不胜感激!

最佳答案

第一个代码块中的函数,定义为

addPow(int n, int p) {

需要您放入原型(prototype)中的额外信息(即返回类型)。它应该看起来像这样:

long long addPow(int n, int p) {

关于c++ - 为什么我不能在声明其内容之前声明一个函数? (c++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42916319/

相关文章:

c++ - 在雷达图像上绘制区域而不是点

c++ - 使用 auto 关键字填充双索引 vector

c++ - 带有友元函数的前向声明 : invalid use of incomplete type

c++ - 以下是否等同于前向声明?

c++ - 如何指定用于保存模型的设备

c++ - 该字段太小,无法接受您在写入 Excel 时尝试添加的数据量

c++ - 使用 c++11 的代码块中出现奇怪的段错误

c++ - 即使我知道我将使用哪个泛型,转发声明模板类是否安全?

c++ - 为什么这是 C++ 中的前向声明?

c++ - C++中的前向声明