在C++中,类static变量独立于实际的对象。static变量在类中定义,并且不能附值,需要在类的外面有且仅有定义和初始化静态变量一次。 由于整个类共享静态变量,所以在类外部定义和初始化静态变量时须将其放到任何一个cpp文件中,不能放在.h文件中,否则当多个cpp文件包含h文件时,就会出现对静态变量的多重定义,引起error LNK2005错误。 例如在Compression.h文件中类Compression声明如下:
这样在编译时就会出现error LNK2005错误,因为static变量的定义和初始化与类在同一个文件,当多个文件包含该文件时,就会对该static变量多重定义。所以应该改为: 在Compression.h文件中类Compression声明如下:
将set< string > Compression::removedRelation;语句放到cpp文件中,即可编译通过。
class Compression
{
private:
static set< string > removedRelation;
vector< destToken > destSentence;
public:
void compression(vector< sourceToken >& sourceSentence);
int getDestSentence(string& str);
static int initRemovedRelation(const string filename);
};
set< string > Compression::removedRelation;
class Compression
{
private:
static set< string > removedRelation;
vector< destToken > destSentence;
public:
void compression(vector< sourceToken >& sourceSentence);
int getDestSentence(string& str);
static int initRemovedRelation(const string filename);
};
本文详细介绍了C++中类静态变量的特性,如何正确地在类外部定义和初始化静态变量,避免编译时的错误LNK2005,并通过实例演示了正确的实现方式。
1万+

被折叠的 条评论
为什么被折叠?



