我是初学者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++
编译器编译它:
g++ -c Test.cpp
此产生的Test.o
文件。
现在在我的体内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:我使用的是Mac Pro 64位版。
如果您确实需要在标头中声明全局对象,请尝试以下操作:
// 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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句