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

2022-01-05 00:00:00 class static linker-errors c++

我希望我能对类的静态变量进行一些说明.

I was hoping I could get some clarification on static variables of a class.

例如:我有两个不同的类,它们执行完全不同的功能,alpha 和 beta.在 alpha 中,我声明了一个类型为 beta 的静态变量,如下所示:

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:

//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:

错误 LNK2001: 未解析的外部符号 "public: static class betaalpha::var" (?var@alpha@@2Vbeta@@A)

error LNK2001: unresolved external symbol "public: static class beta alpha::var" (?var@alpha@@2Vbeta@@A)

我不确定要更改什么或我还需要添加什么才能使这样的工作正常工作.我希望 x、y 和 z 基本上共享相同的 beta 变量.我想我可以通过将一个 beta 变量传递给每个变量来完成同样的事情.但是我想知道是否可以在这里使用 static 关键字来做同样的事情,因为类的静态成员在类的任何实例中都具有相同的值.除非我的定义有误.

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:

把它放在 main.cpp 中:

Put this in main.cpp:

beta alpha::var;

相关文章