在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
我無法理解如何在主函數中使用全局對象。
因爲它違反封裝的概念..你能告訴我一些我們需要這個概念的情況。 – Kenta
@viku:它是如何違反封裝?這是它在C++中完成的方式(如果您必須使用全局變量,本身就是封裝違規)。 – molbdnilo
@viku:我不希望在評論中開始一個單獨的討論,而是鼓勵你制定併發布這個新問題。 – NPE