2013-03-24 136 views
0

我想确保一个模块只加载只有一次,但是当我做我的方式,编译器吐出“未定义参考我的两个静态类变量:S静态变量未定义参考

class Text : public Parent 
{ 
    private: 
     static int Instances; 
     static HMODULE Module; 

    public: 
     Text(); 
     Text(Text&& T); 
     Text(std::wstring T); 
     ~Text(); 

     virtual Text& operator = (Text&& T); 
}; 

Text::Text() : Parent() {} 

Text::~Text() 
{ 
    if (--Instances == 0) 
     FreeLibrary(Module); // Only free the module when 
          // no longer in use by any instances. 
} 

Text::Text(Text&& T) : Parent(std::move(T)), Module(std::move(T.Module)) 

Text::Text(std::wstring T) : Parent(T) // Module only loads when 
             // this constructor is called. 
{ 
    if (++Instances == 1) 
    { 
     Module = LoadLibrary(_T("Msftedit.dll")); 
    } 
} 

Text& Text::operator = (Text&& T) 
{ 
    Parent::operator = (std::move(T)); 
    std::swap(T.Module, this->Module); 
    return *this; 
} 

任何想法,为什么它说未定义参考两个变量(实例&模块)?

+0

定义和类的实现是在同一个文件中还是在单独的文件?错误消息指向哪里? – gongzhitaao 2013-03-24 02:57:46

+0

它指向包含该类定义的Cpp文件。标题和cpp文件是分开的。不提供行号。 – Brandon 2013-03-24 03:01:58

+0

[未定义的引用静态变量]的可能的重复(http://stackoverflow.com/questions/14331469/undefined-reference-to-static-variable) – jogojapan 2013-05-30 14:37:57

回答

1

你应该在你的定义您的静态变量,然后才能使用它。

添加

int Text::Instancese = 0 // whatever value you need. 

顶部你的.cpp文件。

+0

哇..那工作..虽然:为什么不理解为什么你要在实现文件中声明一个变量。我从来没有见过这个。 – Brandon 2013-03-24 03:07:21

+0

@CantChooseUsernames这是C++ :)我认为任何关于C++的介绍都有一个解释:D google它。 – gongzhitaao 2013-03-24 03:08:59

+2

@CantChooseUsernames你不*声明*它 - 你*定义*它。 – 2013-03-24 03:09:02

1

该类定义声明两个静态数据成员Text::InstancesText::Module。如果代码实际使用它们,您还必须定义这些数据成员。就像void f();声明一个函数,但是你不能调用它,除非你也是定义为它。所以加上:

int Text::Instances; 
HMODULE Text::Module; 

到你的源代码。 (这与你的当前代码是完全写在一个头文件中还是分成头文件和源代码无关;如果你使用它,你必须定义它)

+0

谢谢。我纠正了我的答案。 – gongzhitaao 2013-03-24 15:16:44