Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
696 views
in Technique[技术] by (71.8m points)

class - 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. 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:

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

static variables inside a class must still be defined somewhere, just like methods:

Put this in main.cpp:

beta alpha::var;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...