未定义的静态变量和静态方法的引用

时间:2013-10-20 14:38:49

标签: c++ debugging static static-methods

#include <iostream>
using namespace std;

class Assn2
{
  public:
     static void set_numberofshape();
     static void increase_numberofshape();

  private:         
      static int numberofshape22;
};

void Assn2::increase_numberofshape()
{
  numberofshape22++;
}

void Assn2::set_numberofshape()
{
  numberofshape22=0;
} // there is a problem with my static function declaration

int main()
{
  Assn2::set_numberofshape();
}

编译时为什么会出现错误undefined reference to Assn2::numberofshape22

我试图声明一个静态整数:numberofshape22和两个方法。

方法1将numberofshapes22增加1

方法2将numberofshape22初始化为0

我做错了什么?

2 个答案:

答案 0 :(得分:4)

您刚刚声明了变量。你需要定义它:

int Assn2::numberofshape22;

答案 1 :(得分:2)

  

类的成员列表中的静态数据成员的声明不是定义。

要尊重one Definition Rule,您必须定义 static数据成员。在你的情况下,你只是声明它。

示例:

// in assn2.h
class Assn2
{
  // ...
  private:         
      static int numberofshape22; // declaration
};

// in assn2.cpp

int Assn2::numberofshape22; // Definition
相关问题