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
807 views
in Technique[技术] by (71.8m points)

c++ - Undefined reference to a static member of the class

I am working on a homework assignment, and I have almost everything done except for this obnoxious static value that our professor wishes us to use: value

The header file contains:

private:
    static int value;

And we have to have a function calculate the value, like so:

static void calculate()
{
    long a = 1L;
    int count = 0;

    while( a != 0 )
    {
        a = a << 1;
        count++;
    }

    value = count;
}

This is essentially calculating the number of bits in a long, using bit shifting.

However, I am getting the error " undefined reference to `Class1::value'

I've spent the last hour and a half figuring this out, and it's killing me. Any help would be great, all searches have come up dead.

Thanks!


Update:

I included

int Class1::value = 0;

However, now I am getting an error saying "error: int Class1::value is private

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

In your *.cpp file add

int ClassName::value = 0;

This will allocate storage for a value.

The piece of code that you actually have in a class declaration just declares this variable (makes the compiler aware that such a variable exists). However, each variable must be declared and defined. A definition will make sure the storage is put aside for this variable and create a symbol your compiler was unable to find before.


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

...