2014-09-26 22 views
0

我是初學C++程序員。所以這聽起來可能是一個非常簡單的問題。但我仍然感到困惑。C++中的全局對象表示重複的符號

我一直在想,爲什麼C++中的類以分號結尾,(;)如unionstruct。所以我創建了這個類文件。

// Test.h 
#ifndef TEST_H 
#define TEST_H 

#include <iostream> 
using namespace std; 

class Test { 

    public: 
     Test(); 
     ~Test(); 
     void setName(string); 
     string getName(); 

    private: 
     string name; 
} test1, test2; // This is what I called a `global object` 

#endif 

現在我創造了這樣一個實現:

// Test.cpp 
#include "Test.h" 
#include <iostream> 
using namespace std; 


Test::Test() { 

    cout << "Object created" << endl; 
} 

Test::~Test() { 

    cout << "Object destroyed" << endl; 
} 

void Test::setName(string name) { 

    this->name = name; 
} 

string Test::getName() { 

    return name; 
} 

Test.cpp編譯成功。

g++ -c Test.cpp 

這產生Test.o文件:我用它編譯g++這樣的編譯。

現在在我的Main.cpp,這是我有:

// Main.cpp 
#include "Test.h" 
#include <iostream> 
using namespace std;  

int main() { 

    /* I did not declare test1 and test2 in main as they are already global. */ 

    test1.setName("Smith"); 
    test2.setName("Jones"); 

    cout << test1.getName() << endl; 
    cout << test2.getName() << endl; 

    return 0; 
} 

問題在編譯Main.cpp出現了:

當我編譯它是這樣的:

g++ Main.cpp Test.o -o Test 

它給我以下錯誤:

duplicate symbol _test1 in: 
/var/folders/4q/9x9vs76s6hq2fpv11zwtxmvm0000gn/T/Main-a59cee.o 
Test.o 
ld: 1 duplicate symbol for architecture x86_64 
clang: error: linker command failed with exit code 1 (use -v to see invocation) 

那麼我應該如何得到這個工作?任何幫助?
在此先感謝:)

PS:我在一個macbook pro 64位。

+0

還有一個建議,你說你是C++的初學者。尤其是避免在頭文件中使用'namespace'語句。當我們在cpp文件中實現名稱空間時,我們可以聲明'using namespace'。 – elimad 2014-09-26 12:03:55

+0

} test1,test2 ...允許,但不尋常,並導致您的問題。單獨聲明與定義。 – 2014-09-26 12:19:49

回答

1

如果你真的需要聲明的頭全局對象,那就試試這個:

// Test.h 
#ifndef TEST_H 
#define TEST_H 

#include <iostream> 
using namespace std; 

class Test { 

    public: 
     Test(); 
     ~Test(); 
     void setName(string); 
     string getName(); 

    private: 
     string name; 
}; 
extern Test test1, test2; // This is what I called a `global object` 

#endif 
在實現文件(Test.cpp的)

現在,它們定義:

// Test.cpp 
    Test test1, test2; 
// continue your implementation of the class Test as earlier 
+0

Thankyou :)這工作。 – 2014-09-26 14:31:23

1

通過定義變量在一個頭文件中,並且包含來自多個文件的頭文件,您不止一次地定義它們。這是一個錯誤:One Definition Rule指出全局變量只能在程序中定義一次。

要修復它,請將變量定義移動到源文件中; Test.cpp在這裏是合適的;並在標題中聲明它們extern,以便它們可以從其他源文件中獲得。

// Test.h 
extern Test test1, test2; 

// or combine with the class definition if you really want 
extern class Test { 
    // ... 
} test1, test2; 

// Test.cpp 
Test test1, test2; 
+0

謝謝:)這工作。 – 2014-09-26 14:30:50