Compare static and non-static integer in non-static function [closed]

时间秒杀一切 提交于 2019-12-13 07:08:50

问题


I have a static variable that I use as a counter and a non-static version of the variable that I use to save the value of the counter at certain events. Here is some code:

Header:

static int UndoID;
int UndoRedoID;

void SetUnsavedChanges();

Class:

At various parts of the class I try something like this:

UndoRedoID = UndoID;

I've tried other things like:

UndoRedoID = myClass:UndoID;

Example comparision:

void myClass::SetUnsavedChanges()
{
    if (UndoRedoID != UndoID)
    {
        cout << "Unsaved";
    }
    else
    {
        cout << "Saved";
    }
}

This causes me to get linking errors like:

Undefined symbols:
  "myClass::UndoID", referenced from:
    myClass::SetUnsavedChanges()       in myClass_lib.a(myClass.o)
    ...

Thank you for your help :)


回答1:


You need to define the static member data, outside the class as:

//this should be done in .cpp file
int myClass::UndoID;

Let me add one example:

//X.h
class X
{
   static int s; //declaration of static member
};

then in X.cpp file, you should do this:

//X.cpp
#include "X.h"

int X::s; //definition of the static member


来源:https://stackoverflow.com/questions/9928373/compare-static-and-non-static-integer-in-non-static-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!