C++ 私有静态成员变量

Sun*_*day 2 c++ static-methods static-members linker-errors

此 C++ 代码在编译时产生链接器错误:

// 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();
}
Run Code Online (Sandbox Code Playgroud)

将向量声明移动到 cpp 文件中是可行的。但是我想了解"Undefined symbols"上面代码中的链接器错误原因。是什么导致了上述代码中的链接器错误?

nam*_*ero 5

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

// A.cpp

vector<int> A::v;
Run Code Online (Sandbox Code Playgroud)