静态变量和初始化

时间:2015-04-20 02:34:54

标签: c++ static-members

我试图从MyClass.cpp到达MyClass.h中声明的静态变量。但我得到以下错误。 我做了一个研究,但仍然不知道为什么我的代码不编译。我使用visual studio 2013。

MyClass.h

#ifndef __MyClass_h_
#define __MyClass_h_
class MyClass {
static int x;
public:
static int y;   
};
#endif

MyClass.cpp

#include "MyClass.h"
void MyClass::sor() (const string& var1, const unsigned count) const {
    // What goes here? See below for what I have tried
}

所以,如果我使用:

int MyClass::x=8;

这表示int MyClass::x redefinitionMyClass::x 'MyClass::x' : definition or redeclaration illegal in current scope

如果我使用:

    MyClass::x=8;

这会产生错误1 unresolved external

如果我使用:

    MyClass::y=8;

这也会出现错误1 unresolved external

如果我使用:

    int MyClass::y=8;

这表示int MyClass::y redefinition'MyClass::y' : definition or redeclaration illegal in current scope

4 个答案:

答案 0 :(得分:1)

您需要了解自己在标题中没有静态变量,其他答案如何建议。你有一个类的静态成员,这非常好。

要访问它,请编写:MyClass::x。您还需要初始化它。

与静态成员无关,您还需要声明该方法:

头:

#ifndef __MyClass_h_
#define __MyClass_h_
class MyClass {
  static int x;
public:
  static int y;   

  void sor() (const string& var1, const unsigned count) const;
};
#endif

源文件:

#include "MyClass.h"
int MyClass::x = 0; // intialization

void MyClass::sor() (const string& var1, const unsigned count) const {
    MyClaxx::x = 11; // access it

}

答案 1 :(得分:0)

您对静态变量有声明,但没有定义。要使用静态类成员,您应该在相应的翻译单元中定义它们。您不能在头文件中执行此操作,因为它将违反ODR(一个定义规则),因此您应该在.cpp文件中定义它以克服上述规则。

因此,您必须将int MyClass::x = 0;放在全局范围内的cpp文件中(如果有的话,放在命名空间下)以使其正常工作。请注意,您可以使用0所提供的任何值,或者甚至不提供任何值(在这种情况下,由于对全局(静态)变量的特殊处理,它将为0)。

答案 2 :(得分:-1)

  

在头文件中声明静态变量时,其范围仅限于.h文件或所有单位。

Refer here for source

答案 3 :(得分:-1)

这很简单。当您在头文件中declare a static variable时,它的范围仅限于头文件。当您要在static variable文件中使用.cpp时,您会得到error这样的内容。这是因为你没有给出静态变量的definition。因此,在任何.cpp文件中,您需要提供static变量的定义。例如:

.h文件

class MyClass {
static int x;
.....
}

.cpp文件的顶部你应该像这样定义静态变量。

#include "MyClass.h"
int MyClass::x = 0 ;

void MyClass::sor() (const string& var1, const unsigned count) const {
    MyClass::x = 8 ;  // you can access without any issue
}
相关问题