5

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)
{ ....
4

3 に答える 3

7

関数を呼び出すのに定義は必要ありません。必要なのは宣言だけです。コンパイラは、宣言だけで満足しています。リンカーはコードを生成する必要があり、定義が必要ですが、いつ定義するかは問題ではありません。

あなたの場合、すべてのメンバー関数の宣言は、後でクラス定義内にある場合でも、他のすべてのメンバー関数に表示されます。

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

クラスの外では、これは当てはまりません。つまり、メソッドを使用する前に宣言が必要です。宣言は単なるプロトタイプです。

void foo();
void goo()
{
    foo(); //can call foo here even if it's just declared and not defined
}
于 2012-07-14T18:03:21.917 に答える
2

Presumably because they were declared somewhere above (e.g. 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 (i.e. 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 (i.e. its body) is not relevant for this task.

于 2012-07-14T18:03:15.820 に答える
0

それらをいつ定義するかを選択できます。

于 2012-07-14T18:06:13.600 に答える