Why prototype is required even without any class declaration?

前端 未结 3 1902
故里飘歌
故里飘歌 2021-01-14 00:55

If I just do it: Ex1:

#include 

int main()
{
    //try to call doSomething function
    doSomething();
}

void doSomething(         


        
相关标签:
3条回答
  • 2021-01-14 01:46

    You can't call a function without the compiler having seen either the definition or a declaration, first -- simple as that. A prototype or the actual definition must appear before a call.

    0 讨论(0)
  • 2021-01-14 01:47

    This is a legacy from C. C is a single pass language which means that it has to do everything by only reading the file once. To be able to call a function without a forward declaration/prototype would require reading the file twice; The first time to find all the function signatures and the second time to actually compile.

    C++ kept this requirement for features that were part of C, such as free functions and global variables. However classes are new to C++ and there was no need to keep the old way of doing things. So within a single class definition, multi-pass compilation is used. That's why you can do this:

    class MyClass {
        void foo() {bar();}
        void bar() {}
    };
    

    But you can't do what you listed in your question.

    0 讨论(0)
  • 2021-01-14 01:49

    Because the compiler hasn't seen doSomething before it's used.

    Either you must prototype it, or define it first, so that the compiler knows how to analyze the usage of it.

    0 讨论(0)
提交回复
热议问题