Compilation failed, c++ program with static variable as private member variable [duplicate]

眉间皱痕 提交于 2021-01-28 06:45:56

问题


Possible Duplicate:
undefined reference to static member variable
What is an undefined reference/unresolved external symbol error and how do I fix it?

#include<iostream>
using namespace std;

class abc {

    private:
    static int a ;

    public:

    abc(int x) {
        a = x;
    }

    void showData() {
        cout<<"A = "<<a<<endl;
    }
};

int main() {
    abc a1(4);
    abc a2(5);

    a1.showData();
    a2.showData();

    return 0;
}

When I try to compile this function on Ubuntu with GCC compiler. I get the following error.

/tmp/ccCKK2YN.o: In function `main':
static1.cpp:(.text+0xb): undefined reference to `Something::s_nValue'
static1.cpp:(.text+0x14): undefined reference to `Something::s_nValue'
collect2: ld returned 1 exit status
Compilation failed.

Where as the following code runs fine

#include<iostream>
using namespace std;

class Something
{
public:
    static int s_nValue;
};

int Something::s_nValue = 1;

int main()
{
    Something cFirst;
    cFirst.s_nValue = 2;

    Something cSecond;
    std::cout << cSecond.s_nValue;

    return 0;
}

Is this because Static member variables needs to initialized explicitly before accessing them via objects.Why so ?


回答1:


static int s_nValue; doesn't allocate any storage to store the int, it just declares it.

You allocate somewhere in memory to store the variable with:

int Something::a=0;



回答2:


The declaration of a static data member in the member list of a class is not a definition. You must define the static member outside of the class declaration, in namespace scope.

See this thread.

In short, the static member needs to be initialized somewhere in a .cpp file so that the compiler allocates space for it. The declaration would look like this:

int abc::a = 0;



回答3:


That happens because since static members are shared between all instances of a class, they need to be declared in one single place.

If you define the static variable inside the class declaration then each include to that file would have a definition to that variable (which is against to the static meaning).

Because of that you have to define the static members in the .cpp.



来源:https://stackoverflow.com/questions/13125662/compilation-failed-c-program-with-static-variable-as-private-member-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!