2012-12-17 43 views
3

的引用我正在編寫一些代碼來標記對網站所做的更改。我遇到了在類中使用靜態變量的問題,所以我想在名稱空間中聲明一個變量,並在進行更改時設置此== 1。未定義對<namespace> :: <variable>

這裏是我寫來表示問題的一些簡單的代碼:

pH值:

#include<iostream> 
using namespace std; 

#ifndef p_H 
#define p_H 
namespace testing{ 

extern int changes_made; 

class p 
{ 
    public: 
    void changed(); 
    void print_change(); 
    void print_change_ns(); 
    private: 
    static int changes; 
    int info; 
}; 

} 
#endif 

p.cpp:

#include "p.h" 
#include<iostream> 

using namespace testing; 

int p::changes=0; 

void p::changed(){ 
    p::changes=1; 
    } 

void p::print_change(){ 
    cout << p::changes << endl; 
    } 

void p::print_change_ns(){ 
    if (testing::changes_made == 1){ 
    cout << 1 << endl; 
    } 
    else{ 
    cout << 0 << endl; 
    } 
    } 

main.cpp中:

#include<iostream> 
#include"p.h" 

using namespace std; 
using namespace testing; 


int main(){ 

p test1, test2, test3; 
test3.changed(); 
changes_made=1; 

cout << "test1 "; 
test1.print_change(); 
test1.print_change_ns(); 

cout << "test2 "; 
test2.print_change(); 
test2.print_change_ns(); 

cout << "test3 "; 
test3.print_change(); 
test3.print_change_ns(); 

p test4; 
cout << "test4 "; 
test4.print_change(); 
test4.print_change_ns(); 
return 0; 
} 

我得到了fol低的錯誤信息:

p.o: In function `testing::p::print_change_ns()': 
p.cpp:(.text+0x45): undefined reference to `testing::changes_made' 
main.o: In function `main': 
main.cpp:(.text+0x9b): undefined reference to `testing::changes_made' 
collect2: ld returned 1 exit status 

任何幫助,將不勝感激。我以前有多個聲明錯誤,所以我介紹了#ifndef的東西,也是變量之前的extern。

+8

我沒有看到你定義'任何地方changes_made'。 – chris

回答

5

externextern int changes_made;這樣的變量需要在某處創建其存儲。你所說的是「在連接階段,你會發現有人會出口你這個int類型的符號的象徵。

然後你沒有遵守承諾,因爲沒有單位出口int testing::changes_made

在你與上述p.cpp和main.cpp中(甚至p.cpp)鏈接一些.cpp文件,創建變量的一個實例是這樣的:

namespace testing { 
    int changes_made = 0; 
} 

和鏈接器錯誤應該消失。

1

你有在頭文件中聲明爲testing::changes_made;但你沒有定義爲吧。您還需要在一個源文件(可能p.cpp)的定義:

int testing::changes_made; // no "extern" 
相關問題