简体   繁体   English

C ++静态变量和未解决的外部错误

[英]C++ Static variable and unresolved externals error

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. 例如:我有两个不同的类,它们执行完全不同的功能,即alpha和beta。 Within alpha, I declare a static variable of type beta so it looks like this: 在alpha中,我声明了beta类型的静态变量,因此它看起来像这样:

//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(); 
}

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) 错误LNK2001:无法解析的外部符号“ public:静态类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. 我希望x,y和z本质上共享相同的beta变量。 I think I can accomplish this same thing by just passing by reference one beta variable into each of them. 我认为我可以通过仅将一个beta变量传递给每个变量来实现相同的目的。 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. 但是我想知道是否可以在这里使用static关键字来做同样的事情,因为类的静态成员在类的任何实例中都具有相同的值。 Unless I have that definition wrong. 除非我有错误的定义。

static variables inside a class must still be defined somewhere, just like methods: 仍然必须在某处定义类内的静态变量,就像方法一样:

Put this in main.cpp: 把它放在main.cpp中:

beta alpha::var;

Add this to main.cpp: 将此添加到main.cpp中:

beta  alpha::var;

var in h-file is only type declaration. h文件中的var只是类型声明。 Variable should be created in some source file. 变量应在某些源文件中创建。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM