我正在尝试从 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 redefinition
和 MyClass::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/