0

我有一个用作计数器的静态变量和一个用于在某些事件中保存计数器值的变量的非静态版本。这是一些代码:

标题:

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)
    ...

谢谢您的帮助 :)

4

1 回答 1

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
于 2012-03-29T15:21:17.120 回答