简体   繁体   中英

How come these functions are called before being defined?

this is the cpp of a Time function. The code is defining functions of a time.h file on this time.cpp. My question is: How come this function definition is possible if the functions inside this fct are defined afterwards? Thank you

void Time::setTime(int hour, int minute, int second)
{
    sethour(hour);
    setminute(minute);
    setseconds(seconds);
}

void Time::sethour( int h)
{ ....

You don't need a definition to call a function, you only need a declaration. The compiler is happy with the declaration alone. The linker requires code to be generated, and it requires the definition, but it doesn't matter when you define them, as long as you do.

In your case, the declaration of every member function is visible to all other member function, even if inside the class definition it came afterwards:

class Time
{
   void setTime();  //setTime knows about sethour even if it's before
   void sethour();
};

Outside of a class, this doesn't hold, meaning you need a declaration before using a method. The declaration is just the prototype:

void foo();
void goo()
{
    foo(); //can call foo here even if it's just declared and not defined
}

Presumably because they were declared somewhere above (eg in the header file), and that's what's important.

It's best to imagine that the compiler operates in a "one-pass" approach; it processes your code linearly from top-to-bottom. Therefore, it needs to know that functions exist (ie their name, arguments and return type) before they are used, in order to establish that the caller is not doing something invalid. But the actual function definition (ie its body) is not relevant for this task.

您可以选择何时定义它们。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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