Prototyping in C++

混江龙づ霸主 提交于 2019-12-11 10:59:20

问题


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;

}

回答1:


"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. 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?




回答2:


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. (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?




回答3:


You have to declare the full signature of your function, i.e. the name, the return value, all parameters with types, their constness, etc.



来源:https://stackoverflow.com/questions/32207173/prototyping-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!