我有我想要调试的代码。我看起来没问题。但是,我得到一个错误,我不understand.Here的我的代码C++ - 这个单独的编译代码有什么问题?
//struct.h
#ifndef STRUCT_H
#define STRUCT_H
#include <iostream>
using namespace std;
struct Person {
Person();
Person(int a, string n);
Person(const Person &p);
Person &operator=(const Person &p);
~Person();
int age;
string name;
};
#endif
//struct.cc
#include "struct.h"
Person::Person(): age(0), name("noname") {
cout << "Creating default Person" << endl;
}
Person::Person(int a, string n): age(a), name(n) {
cout << "Creating: " << name << "," << age << endl;
}
Person::Person(const Person &p) {
name = p.name;
age = p.age;
}
Person& Person::operator=(const Person &p) {
Person person;
person.name = p.name;
return person;
}
Person::~Person() {
cout << "Destroying: " << name << "," << age << endl;
}
//structMain.cc
#include "struct.h"
#include <iostream>
using namespace std;
int main() {
Person one(21, "Zuhaib");
cout << "I am " << one.name << ". I am " << one.age << " years old" << endl;
Person two;
cout << "I am " << two.name << ". I am " << two.age << " years old" << endl;
two = one;
cout << "I am " << two.name << ". I am " << two.age << " years old" << endl;
}
我
g++ -c struct.cc
g++ -c structMain.cc
g++ -o struct.o structMain.o
编译然后我收到以下错误
structMain.o: In function `main':
structMain.cc:(.text+0x3b): undefined reference to `Person::Person(int, std::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
structMain.cc:(.text+0xb5): undefined reference to `Person::Person()'
structMain.cc:(.text+0x11e): undefined reference to `Person::operator=(Person const&)'
structMain.cc:(.text+0x180): undefined reference to `Person::~Person()'
structMain.cc:(.text+0x18c): undefined reference to `Person::~Person()'
structMain.cc:(.text+0x1b8): undefined reference to `Person::~Person()'
structMain.cc:(.text+0x1e3): undefined reference to `Person::~Person()'
structMain.cc:(.text+0x1f4): undefined reference to `Person::~Person()'
collect2: ld returned 1 exit status
我想我包括所有的正确的文件。我仔细检查了声明和定义。我只是不确定为什么这些错误即将到来。我看起来很好。
此外,在主函数中,什么在该行
two = one;
我不知道这一点,因为,我已经超负荷运营情况=,但我也定义拷贝构造函数也执行时“ =“。所以在上面的例子中,operator = execute或copy构造函数。 任何帮助,将不胜感激。 感谢
请重新考虑您对不良做法['using namespace std;'](http://stackoverflow.com/q/1452721/1171191)和['endl'](http://chris-sharpe.blogspot。 co.uk/2016/02/why-you-shouldnt-use-stdendl.html)。 – BoBTFish
最后一行分隔编辑接缝奇怪。尝试不用'-c'选项 – Garf365
@ Garf365。我很抱歉,那应该是一个-o。我已经改变了它 –