c++入門 (成員變量)

Fields,parameters local variables.                

1. All three kinds of variable are able to store a value that is appropriate to their defined type.

這三種類型都可以存儲一個指定類型的值

2. Fields are defined outside constructors and methods. Fields are used to store data that persists throughout the life of an object.As such, they maintain the current state of an object.They have a lifetime that lasts as long as their object lasts.

成員變量在方法和構造器外面定義,成員變量用來存儲持續對象一生的數據,他們用來保存對象的狀態。他們和對象的生存時間相同

3. Fields have class scope:their accessibility extends throughout the whole class, and so they can be used within any of the constructors or methods of the class in which they are defined.

成員變量是在類的scope內,他們可以被他們所在的類的構造器和方法使用。

-----------------------------------------------------------------

class A{
private :
int a;
public:
void f();
}
extern int g;
int g;


int A::i;
void A::f(){
int j=10;
i=10;
}
int main(){
A a;
a.f();
}

------------------------------------------------------------------------


中間一段代碼拿全局變量g和成員變量A::i做比較,extern int g; 需要 int g;來聲明

二A::i 不需要  int A::I做聲明,只需要A a;的時候,聲明瞭對象a,同時a的成員變量i也會實例化。


-----------------------------------------------------------------

class A{
private :
int a;
public:
void f();
}
extern int g;
int g;


int A::i;
void A::f(){
int j=10;
i=10;
}
int main(){
A a;

printf("&a=%p\n",&a);
printf("&a.i=%p\n",&(a.i));

}

------------------------------------------------------------------------

結果發現a的地址和a.i的地址是相同的。


說明a所在的地址空間包含a.i


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章