制作重载函数的原型c ++

make prototype of overloading function c++

我想用 C++ 中的原型创建一个重载函数。

#include <iostream>

using namespace std;

int rectangle(int p, int l);

int main() {
    cout << rectangle(3);
    return 0;
}

int rectangle(int p) {
    return p*p;
}

int rectangle(int p, int l) {
    return p*l;
}

我在

遇到错误
int rectangle(int p, int l);

是否可以制作具有重载功能的原型?如果可能怎么做

您必须在 use/call 之前声明函数。您确实声明了 rectangle 函数的 2 个参数版本,但您似乎忘记声明采用 1 个参数的版本。

如下所示,如果您为 1 个参数版本添加声明,那么您的程序可以运行(编译)。

#include <iostream>
using namespace std;

//declare the function before main
int rectangle(int p, int l);
int rectangle(int p);//ADDED THIS DECLARATION
int main() {
    cout << rectangle(3);
    return 0;
}
//define the functions after main
int rectangle(int p) {
    return p*p;
}
int rectangle(int p, int l) {
    return p*l;
}

程序输出可见here.

备选方案:

如果您不想单独声明每个函数,那么您应该在 main 之前定义它们,而不是像下面这样声明它们。

#include <iostream>
using namespace std;

//define the functions before main. This way there is no need to write a separate function declaration because all definition are declarations
int rectangle(int p) {
    return p*p;
}
int rectangle(int p, int l) {
    return p*l;
}

int main() {
    cout << rectangle(3);
    return 0;
}