我是初学C++程序员。所以这听起来可能是一个非常简单的问题。但我仍然感到困惑。C++中的全局对象表示重复的符号
我一直在想,为什么C++中的类以分号结尾,(;
)如union
和struct
。所以我创建了这个类文件。
// 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位。
还有一个建议,你说你是C++的初学者。尤其是避免在头文件中使用'namespace'语句。当我们在cpp文件中实现名称空间时,我们可以声明'using namespace'。 – elimad 2014-09-26 12:03:55
} test1,test2 ...允许,但不寻常,并导致您的问题。单独声明与定义。 – 2014-09-26 12:19:49