Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
855 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...