2012-11-26 65 views
3

在Friend.h如何使用用戶定義的全局類對象

#ifndef FRIEND 
#define FRIEND 
class Friend 
{ 

public: 
    static int i ; 
    int j; 
    Friend(void); 
    ~Friend(void); 
}frnd1; 
#endif 

在Friend.cpp

#include "Friend.h" 
int Friend::i = 9; 
extern Friend frnd1; 
Friend::Friend(void) 
{ 
} 

Friend::~Friend(void) 
{ 
} 

在main.cpp中

#include <iostream> 
using namespace std; 
#include"Friend.h" 

int main() 
{ 
frnd1.j = 9; 
cout<<"hello"; 
getchar(); 
return 0; 
} 

當我運行上面的代碼,它給出以下鏈接器錯誤:

error LNK2005: "class Friend frnd1" ([email protected]@[email protected]@A) already defined in main.obj 

我無法理解如何在主函數中使用全局對象。

回答

5

問題是frnd1在頭文件中定義爲,因此最終在每個翻譯單元中被實例化。

你想要做什麼是聲明它在頭文件,並定義它在相應的.cpp文件:

  1. 變化Friend.hclass Friend { ... } frnd1;class Friend { ... };
  2. extern Friend frnd1;加到Friend.h;
  3. extern Friend frnd1;更改爲Friend frnd1;Friend.cpp

Friend.h:

​​

Friend.cpp:

#include "Friend.h" 

Friend frnd1; 
+0

因爲它違反封裝的概念..你能告訴我一些我們需要這個概念的情況。 – Kenta

+0

@viku:它是如何違反封裝?這是它在C++中完成的方式(如果您必須使用全局變量,本身就是封裝違規)。 – molbdnilo

+0

@viku:我不希望在評論中開始一個單獨的討論,而是鼓勵你制定併發布這個新問題。 – NPE

1

extern Friend frnd1;進入標題; Friend frnd1;進入(一).cpp文件。

1

嘗試以下方法:

頭:

class Friend 
{ 
// ... 
}; 

extern Friend frnd1; 

我mplementation:

Friend frnd1; 
相關問題