我有一个静态变量,我用作计数器和变量的非静态版本,用于在某些事件中保存计数器的值。这是一些代码:
部首:
static int UndoID;
int UndoRedoID;
void SetUnsavedChanges();
类别:
在课堂的各个部分,我尝试这样的事情:
UndoRedoID = UndoID;
我尝试过其他类似的事情:
UndoRedoID = myClass:UndoID;
比较示例:
void myClass::SetUnsavedChanges()
{
if (UndoRedoID != UndoID)
{
cout << "Unsaved";
}
else
{
cout << "Saved";
}
}
这导致我得到链接错误,如:
Undefined symbols:
"myClass::UndoID", referenced from:
myClass::SetUnsavedChanges() in myClass_lib.a(myClass.o)
...
感谢您的帮助:)
答案 0 :(得分:2)
您需要在类外部定义静态成员数据:
//this should be done in .cpp file
int myClass::UndoID;
让我举一个例子:
//X.h
class X
{
static int s; //declaration of static member
};
然后在X.cpp
文件中,你应该这样做:
//X.cpp
#include "X.h"
int X::s; //definition of the static member