A class with static member function. Compile error.

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
ImLazy
Experienced poster
Posts: 215
Joined: Sat Jul 10, 2004 4:31 pm
Location: Shanghai, China

A class with static member function. Compile error.

Post by ImLazy »

This is my code:

Code: Select all

#include <iostream>

using namespace std;

class A {
private:
    static int a;

public:
    static void set(int i) {
        a = i;
    }

    static void get() {
        cout << a << endl;
    }
};

int main() {
    A::set(199);
    A::get();
    return 0;
}
This is the compiling result:

Code: Select all

/tmp/ccaeaQQB.o: In function `A::set(int)':
stest.cpp:(.text._ZN1A3setEi[A::set(int)]+0x7): undefined reference to `A::a'
/tmp/ccaeaQQB.o: In function `A::get()':
stest.cpp:(.text._ZN1A3getEv[A::get()]+0x7): undefined reference to `A::a'
collect2: ld returned 1 exit status
This is my compiler version:

Code: Select all

g++ (GCC) 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu5)
Copyright (C) 2006 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
I stay home. Don't call me out.

misof
A great helper
Posts: 430
Joined: Wed Jun 09, 2004 1:31 pm

Post by misof »

If you declare a member variable of a class as static, in C++, you must initialize it globally before using the static member variable.

Code: Select all

#include <iostream>

using namespace std;

class A {
private:
    static int a;

public:
    static void set(int i) {
        A::a = i;
    }

    static void get() {
        cout << A::a << endl;
    }
};
int A::a=0;

int main() {
    A::set(199);
    A::get();
    return 0;
}

ImLazy
Experienced poster
Posts: 215
Joined: Sat Jul 10, 2004 4:31 pm
Location: Shanghai, China

Post by ImLazy »

Thank you.
I stay home. Don't call me out.

Post Reply

Return to “C++”