c++ - 静态变量和初始化

标签 c++ static-members

我正在尝试从 MyClass.cpp 获取在 MyClass.h 中声明的静态变量。但是我收到以下错误。 我进行了研究,但仍然不知道为什么我的代码无法编译。我使用 visual studio 2013。

我的类.h

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

我的类.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

最佳答案

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

为了访问它,你写: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

}

关于c++ - 静态变量和初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29738467/

相关文章:

c++ - 需要使用Sqlite创建一个简单的C++项目

c++ - Qt 2D 寻路游戏中的动画

c++ - 在 C++ 中使用 INetwork::GetNetworkConnections()

c++ - 嵌套类中的静态成员是否具有封闭类的静态持续时间?

c++ - 如何初始化一个 std::map 一次,以便它可以被一个类的所有对象使用?

c++ - 将类内的随机数 boost 为静态成员

c++ - 构造函数中的初始化列表可以在模板类中使用吗?

c++ - 编译器警告使 int8_t 的复合赋值提升为 int 感到困惑

python - 我们如何确定属性属于实例还是类?

c++ - 是否可以在 .cpp 文件而不是其头文件中定义类的静态成员函数?