2013-09-23 164 views
0

這個C++代碼在編譯時生成的鏈接錯誤: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(); 
} 

移動向量聲明爲cpp文件作品。不過,我想了解上述代碼中的鏈接器錯誤"Undefined symbols"原因。上述代碼中導致鏈接器錯誤的原因是什麼?

+1

您缺少''中A.cpp' v'的定義。 –

回答

2

靜態成員編譯單元中定義:

// A.cpp 

vector<int> A::v; 
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(); 
}