close

在compile時 , 在read statement時通常都是sequentially , 所以若有以下的狀況時便會發生錯誤:

#include <iostream>
 
int main()
{
    using namespace std;
    cout << "The sum of 3 and 4 is: " << add(3, 4) << endl;
    return 0;
}

int add(int x, int y)
{
    return x + y;
}

因為compiler在main function前面並沒有看到add function , 所以他會發出complain , 說他並不知道有add function.

而要解決這樣的問題, 我們通常需要在main()前面宣告一個function prototype , 來告知道compiler我們有哪些function 

這樣的方式我們就稱為foward declaration. (function definition can be anywhere in the program , except in front of his foward declaration.)

#include <iostream>
 
int add(int x, int y); // forward declaration of add() using a function prototype
 
int main()
{
    using namespace std;
    cout << "The sum of 3 and 4 is: " << add(3, 4) << endl;
    return 0;
}
 
int add(int x, int y)
{
    return x + y;
}
 
而對於class與class間 以及function間的相互reference , 我們通常也都需要借助 forward declaration來幫我們解決.
 
class Server; // The forward reference.
    class Client 
   {
    public:
         virtual Server server() const;
         virtual void setServer( Server server );
    };
 

ref : http://www.learncpp.com/cpp-tutorial/17-forward-declarations/

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 JerryCheng 的頭像
    JerryCheng

    KwCheng's blog

    JerryCheng 發表在 痞客邦 留言(0) 人氣()