C++ private static member variables

馋奶兔 提交于 2019-12-11 05:29:42

问题


This C++ code is producing linker errors at compile time:

// A.h
class A {
    public:
        static void f();
    private:
        static std::vector<int> v;
};

// A.cpp
void A::f() {
    // this line is causing trouble
    int i = v.size();
}

Moving the vector declaration into the cpp file works. However I want to understand the linker error "Undefined symbols" cause in the above code. What is causing the linker error in the above code?


回答1:


Static members have to be defined in a compilation unit:

// A.cpp

vector<int> A::v;



回答2:


// A.h
class A {
    public:
        static void f();
    private:
        static std::vector<int> v;
};

// A.cpp
//modify add this line
static std::vector<int> A::v;
void A::f() {
    // this line is causing trouble
    int i = v.size();
}


来源:https://stackoverflow.com/questions/18970384/c-private-static-member-variables

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