C ++静态变量和未解析的外部错误 [英] C++ Static variable and unresolved externals error
问题描述
我希望我能对类的静态变量有一些澄清。
例如:
我有两个不同的类,它们执行完全不同的函数alpha和beta。在alpha内,我声明一个类型为beta的静态变量,如下所示:
// alpha.h
#pragma once
#include< iostream>
#includebeta.h
class alpha {
public:
alpha(){
}
static beta var;
void func(){
var.setX(3);
}
void output(){
}
};
//beta.h
#pragma once
#include< iostream>
using namespace std;
class beta {
public:
int x;
char y;
beta(){
x = 0;
y ='';
}
void setX(int _X){
x = _X;
}
};
//main.cpp
#include< iostream>
#include< iomanip>
#includealpha.h
using namespace std;
int main(){
alpha x,y,z;
x.func();
}
错误LNK2001:未解析的外部符号public:static class beta 我不知道要更改什么或需要添加什么来使这样的工作。我想要x,y和z基本上共享相同的beta变量。我想我可以完成同样的事情,只是通过引用一个beta变量到每个他们。但我想知道是否可以做这个相同的事情使用static关键字这里,因为类的静态成员在类的任何实例中具有相同的值。除非我有那个定义错了。 类中的静态变量必须仍然定义在某处,与方法类似: 把它放在main.cpp中: I was hoping I could get some clarification on static variables of a class. For example:
I have two different classes which perform completely different functions, alpha and beta. Within alpha, I declare a static variable of type beta so it looks like this: Now when I try to compile this, I get an unresolved externals error: error LNK2001: unresolved external symbol "public: static class beta
alpha::var" (?var@alpha@@2Vbeta@@A) I'm not sure what to change or what else I need to add to make something like this work. I want x, y, and z to essentially share the same beta variable. I think I can accomplish this same thing by just passing by reference one beta variable into each of them. But I want to know if it's possible to do this same thing using the static keyword here because static members of a class have the same value in any instance of a class. Unless I have that definition wrong. static variables inside a class must still be defined somewhere, just like methods: Put this in main.cpp:
这篇关于C ++静态变量和未解析的外部错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
现在当我尝试编译这个,我得到一个未解决的外部错误: / p>
alpha :: var(?var @ alpha @@ 2Vbeta @@ A)
beta alpha :: var;
//alpha.h
#pragma once
#include <iostream>
#include "beta.h"
class alpha{
public:
alpha(){
}
static beta var;
void func(){
var.setX(3);
}
void output(){
}
};
//beta.h
#pragma once
#include <iostream>
using namespace std;
class beta{
public:
int x;
char y;
beta(){
x = 0;
y = ' ';
}
void setX(int _X){
x = _X;
}
};
//main.cpp
#include <iostream>
#include <iomanip>
#include "alpha.h"
using namespace std;
int main(){
alpha x, y, z;
x.func();
}
beta alpha::var;