作者ric2k1 (Ric)
看板EE_DSnP
標題[討論] 關於 class 編譯的問題
時間Wed Oct 10 20:44:19 2007
請問 class 中的程式碼是按照什麼順序被編譯的呢?
似乎和 main ( ) 很不一樣?
例如 public 中所定義的 member function 可以用到下面 private 中才宣告的 data
member,
constructor 中也可以用到下面才定義的 member function。
這麼一來豈不是要先寫後面再回到前面補程式碼?
=============================================================
I think your question is for program like:
...
class A
{
public:
A(int i) : _data(i) {}
void print() { cout << _data << endl; }
private:
int _data;
};
You are asking why the constructor "A(int)" and the function "print()" can
see and use the data member "int _data" since they are defined BEFORE the
variable "_data"?
This is a good observation. For anything outside the "class" definition, yes,
the function or variable must be declared before they can be defined and used.
However, for the data member and member functions in a class, there is no such
restriction. The compiler will scan through the class and create the symbol
table first and then do the compilation. So as long as the compiler can find
the symbols within the same class scope, it is OK to use them.
So the following code is also OK.
class A
{
public:
A(int i) : _data(i) { init(); }
// call the function init()
void init() { .... }
void print() { cout << _data << endl; }
void f() { g(); }
// calling g() even it's not defined in this class
int g(); // g() is defined outside the class
private:
int _data;
};
But of course, the following is NOT OK.
int main()
{
f();
// Error: f() is defined below this line
}
void f()
{
...
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 59.121.131.190