简体   繁体   English

C ++中的原型

[英]Prototyping in C++

If I prototype a function above the main function in my code, do I have to include all parameters which have to be given? 如果我在代码中的主要功能之上原型化了一个功能,是否必须包括所有必须给出的参数? Is there a way how I can just prototype only the function, to save time, space and memory? 有没有一种方法可以仅对函数进行原型设计以节省时间,空间和内存?

Here is the code where I came up with this question: 这是我想到这个问题的代码:

#include <iostream>

using namespace std;

int allesinsekunden(int, int, int);

int main(){
    int stunden, minuten, sekunden;

    cout << "Stunden? \n";
    cin >> stunden;
    cout << "Minuten? \n";
    cin >> minuten;
    cout << "Sekunden= \n";
    cin >> sekunden;

    cout << "Alles in Sekunden= " << allesinsekunden(stunden, minuten, sekunden) << endl;
}

int allesinsekunden (int h, int m, int s) {
    int sec;

    sec=h*3600 + m*60 + s;

    return sec;

}

"If I prototype a function above the main function in my code, do I have to include all parameters which have to be given?" “如果我在代码中的主要功能之上原型化一个功能,是否必须包括所有必须给出的参数?”

Yes, otherwise the compiler doesn't know how your function is allowed to be called. 是的,否则编译器不知道如何调用您的函数。
Functions can be overloaded in c++, which means functions with the same name may have different number and type of parameters. 函数可以在c ++中重载,这意味着具有相同名称的函数可能具有不同数量和类型的参数。 Such the name alone isn't distinct enough. 仅仅这样的名字还不够鲜明。

"Is there a way how I can just prototype only the function, to save time, space and memory?" “有没有一种方法可以只对函数进行原型设计,以节省时间,空间和内存?”

No. Why do you think it would save any memory? 否。为什么您认为它可以节省任何内存?

No, because it would add ambiguity. 不,因为这会增加歧义。 In C++ it's perfectly possible to have two completely different functions which differ only in the number and/or type of input arguments. 在C ++中,完全有可能拥有两个完全不同的函数,它们的区别仅在于输入参数的数量和/或类型。 (Of course, in a well-written program what these functions do should be related.) So you could have (当然,在编写良好的程序中,这些功能的作用应该相关。)因此,您可以

int allesinsekunden(int, int, int)
{
//...
}

and

int allesinsekunden(int, int)
{
//...
}

If you tried to 'prototype' (declare) one of these with 如果您尝试使用以下方法之一“原型”(声明)

int allesinsekunden;

how would the compiler know which function was being declared? 编译器如何知道正在声明哪个函数? Specifically how would it be able to find the right definition for use in main ? 具体来说,如何找到适合main的正确定义?

您必须声明函数的完整签名,即名称,返回值,带有类型的所有参数,它们的常数等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM