我最近开始学习面向对象的编程..对于以下代码,我收到链接器错误!!
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
class person{
public:
string name;
person();
person(string n){
name = n ;
}
void setName(string k){
name = k;
}
string getName(){
return name;
}
};
class student : public person {
public:
string major;
void setMajor(string m){
major = m;
}
string getMajor(){
return major;
}
};
class faculty : public person{
public:
string department;
faculty(string dept){
department = dept;
}
void setDepartment(string depart){
department = depart;
}
string getDepartment(){
return department;
}
};
int main() {
student s;
s.setName("james");
s.setMajor("computer science");
string p = s.getName();
string p2 = s.getMajor();
cout << "student name and mjor is :" << p << p2 << endl;
faculty f("nanotech");
f.setName("chris");
f.setDepartment("electrical");
string f1 = f.getName();
string f2 = f.getDepartment();
cout << "facult name and department :" << f1 << f2 << endl;
return 0;
}
当我尝试编译代码时,我得到以下错误。
/tmp/ccYHu2de.o: In function `faculty::faculty(std::string)':
person.cpp:(.text._ZN7facultyC2ESs[_ZN7facultyC5ESs]+0x19): undefined reference to `person::person()'
/tmp/ccYHu2de.o: In function `student::student()':
person.cpp:(.text._ZN7studentC2Ev[_ZN7studentC5Ev]+0x15): undefined reference to `person::person()'
collect2: error: ld returned 1 exit status
答案 0 :(得分:0)
在你的班级中,你有一个声明但未定义的构造函数。编译器允许您编译类,但链接器会查找实现(称为forward declaration):
class person{
public:
string name;
person(); //constructor only declared
person(string n){
name = n ;
}
.....
};
问题是你从学生和教职员工那里继承,你使用默认的构造函数,但你从未实现它。尝试添加实现,链接器错误将消失:
class person{
public:
string name;
person(){} //constructor implemented
person(string n){
name = n ;
}
.....
};
答案 1 :(得分:0)
问题是你需要实现person类的构造函数,试试这段代码:http://ideone.com/NfXP7R
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
class person{
public:
string name;
person() {
}
person(string n){
name = n ;
}
void setName(string k){
name = k;
}
string getName(){
return name;
}
};
class student : public person {
public:
string major;
void setMajor(string m){
major = m;
}
string getMajor(){
return major;
}
};
class faculty : public person{
public:
string department;
faculty(string dept){
department = dept;
}
void setDepartment(string depart){
department = depart;
}
string getDepartment(){
return department;
}
};
int main() {
student s;
s.setName("james");
s.setMajor("computer science");
string p = s.getName();
string p2 = s.getMajor();
cout << "student name and mjor is :" << p << p2 << endl;
faculty f("nanotech");
f.setName("chris");
f.setDepartment("electrical");
string f1 = f.getName();
string f2 = f.getDepartment();
cout << "facult name and department :" << f1 << f2 << endl;
return 0;
}