靜態成員函數解析

靜態數據成員:
下面看一個例子:
#include <iostream.h>
class  Point
{
public:
 void output()
 {
 }
 static void init()
 {  
 } 
};
void main( void )
{
 Point pt;
 pt.init();
 pt.output();  
}
這樣編譯是不會有任何錯誤的。
下面這樣看
#include <iostream.h>
class  Point
{
public:
 void output()
 {  
 }
 static void init()
 {  
 } 
};
void main( void )
{
 Point::output();
}
這樣編譯會處錯,錯誤信息:illegal call of non-static member function,爲什麼?
因爲在沒有實例化一個類的具體對象時,類是沒有被分配內存空間的。
好的再看看下面的例子:
#include <iostream.h>
class  Point
{
public:
 void output()
 {  
 }
 static void init()
 {  
 } 
};
void main( void )
{
 Point::init();
}
這時編譯就不會有錯誤,因爲在類的定義時,它靜態數據和成員函數就有了它的內存區,它不屬於類的任何一個具體對象。
好的再看看下面的例子:
#include <iostream.h>
class  Point
{
public:
 void output()
 {  
 }
 static void init()
 { 
  x = 0;
  y = 0;
 }
private:
 int x;
 int y;
};
void main( void )
{
 Point::init();
}
編譯出錯:
illegal reference to data member 'Point::x' in a static member function
illegal reference to data member 'Point::y' in a static member function
在一個靜態成員函數裏錯誤的引用了數據成員,
還是那個問題,靜態成員(函數),不屬於任何一個具體的對象,那麼在類的具體對象聲明之前就已經有了內存區,
而現在非靜態數據成員還沒有分配內存空間,那麼這裏調用就錯誤了,就好像沒有聲明一個變量卻提前使用它一樣。
也就是說在靜態成員函數中不能引用非靜態的成員變量。
好的再看看下面的例子:
#include <iostream.h>
class  Point
{
public:
 void output()
 {
  x = 0;
  y = 0;
  init();  
 }
 static void init()
 { 

 }
private:
 int x;
 int y;
};
void main( void )
{
 Point::init();
}
好的,這樣就不會有任何錯誤。這最終還是一個內存模型的問題,
任何變量在內存中有了自己的空間後,在其他地方纔能被調用,否則就會出錯。
好的再看看下面的例子:
#include <iostream.h>
class  Point
{
public:
 void output()
 { 
 }
 static void init()
 { 
  x = 0;
  y = 0;
 }
private:
 static int x;
 static int y;
};
void main( void )
{
 Point::init();
}
編譯:
Linking...
test.obj : error LNK2001: unresolved external symbol "private: static int Point::y" (?y@Point@@0HA)
test.obj : error LNK2001: unresolved external symbol "private: static int Point::x" (?x@Point@@0HA)
Debug/Test.exe : fatal error LNK1120: 2 unresolved externals
執行 link.exe 時出錯.
可以看到編譯沒有錯誤,連接錯誤,這又是爲什麼呢?
這是因爲靜態的成員變量要進行初始化,可以這樣:
#include <iostream.h>
class  Point
{
public:
 void output()
 { 
 }
 static void init()
 { 
  x = 0;
  y = 0;
 }
private:
 static int x;
 static int y;
};
int Point::x = 0;
int Point::y = 0;
void main( void )
{
 Point::init();
}
在靜態成員數據變量初始化之後就不會出現編譯錯誤了。
再看看下面的代碼:
#include <iostream.h>
class  Point
{
public:
 void output()
 { 
 }
 static void init()
 { 
  x = 0;
  y = 0;
 }
private:
 static int x;
 static int y;
};
void main( void )
{
}
編譯沒有錯誤,爲什麼?
即使他們沒有初始化,因爲我們沒有訪問x,y,所以編譯不會出錯。

發佈了18 篇原創文章 · 獲贊 6 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章