2014-09-26 76 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