2013-03-12 77 views
6

嗨IAM初學者++我有靜態方法類,我不能訪問他們來說,這將引發我一個錯誤C++解析外部符號位於C

1>------ Build started: Project: CPractice, Configuration: Debug Win32 ------ 
1> Source.cpp 
1>Source.obj : error LNK2001: unresolved external symbol "private: static class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > CPractice::name" ([email protected]@@[email protected][email protected]@[email protected]@[email protected]@[email protected]@[email protected]@A) 
1>c:\users\innersoft\documents\visual studio 2012\Projects\CPractice\Debug\CPractice.exe : fatal error LNK1120: 1 unresolved externals 
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== 

,這裏是我的代碼

#include <iostream> 
#include <stdio.h> 
#include <cstdlib> 
#include <string> 

using namespace std; 

class CPractice 
{ 
    public: 
     static void setName(string s) 
     { 
      name = s; 
     } 
     static string getName() 
     { 
      return name; 
     } 
    private: 
     static string name; 
}; 


int main() 
{ 


    CPractice::setName("Name"); 
    cout << "\n" << CPractice::getName(); 
    system("PAUSE"); 
    return EXIT_SUCCESS; 
} 

回答

18
static string name; 

因爲它是static,這條線只有宣佈name - 你也需要定義它。只要把下面這個類定義:

string CPractice::name; 

如果你最終你的類移動到相應的頭文件和實現文件,請確保你把這個定義在實現文件。它只應在單個翻譯單元中定義。

+0

我認爲它的媒體鏈接定義的,當我宣佈它。它的作品,非常感謝 – 2013-03-12 19:24:09

+1

@SilvioMarijic這是人們常見的錯誤。它不是一個定義的原因是避免有多個定義。如果它是一個定義,並且包含了許多其他文件的頭文件,那麼您將擁有多個相同靜態成員的定義。無論如何,不​​要忘了通過接受最能幫助你的答案來表示感謝。 – 2013-03-12 19:38:35

1

您只能在類中聲明name,靜態變量需要像這樣定義的類之外:

string CPractice::name ="hello" ; 
1

由於名字是靜態數據成員應該初始化:)和不計在默認實例相關的構造函數上。

在類的定義添加這個(是的,我知道它的混亂,因爲你的會員是一個私人性質,但是這僅僅是一個初始化):

string CPractice::name;