C++ 類中的靜態變量


C++ 類中的靜態變量
 

轉自http://blog.csdn.net/zieckey/archive/2006/11/23/1408767.aspx

作者:zieckey 一切權利歸作者所有

靜態數據成員:
下面看一個例子:
#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;
};


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM