C++ private static member variables

2019-08-13 15:14发布

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?

2条回答
【Aperson】
2楼-- · 2019-08-13 15:38

Static members have to be defined in a compilation unit:

// A.cpp

vector<int> A::v;
查看更多
forever°为你锁心
3楼-- · 2019-08-13 15:48
// 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();
}
查看更多
登录 后发表回答