2

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?

4

2 回答 2

5

静态成员必须在编译单元中定义:

// A.cpp

vector<int> A::v;
于 2013-09-23T23:14:41.323 回答
3
// 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();
}
于 2013-09-23T23:14:17.960 回答