2013-10-20 214 views
1
#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 INITIALISE numberofshape22 0

我在做什么错?

回答

4

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

int Assn2::numberofshape22; 
2

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

要尊重one Definition Rule必须定义一个static数据成员。在你的情况下,你只是宣布它。

例子:

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

// in assn2.cpp 

int Assn2::numberofshape22; // Definition 
+0

哇...感谢。 – Erutan409