作者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