C 中的基类未定义错误

Base class undefined error in C++

本文关键字:未定义 错误 基类      更新时间:2023-10-16

----更新---

我在项目中包括标题和CPP文件时遇到问题,因此这里是文件:person.h

#ifndef PERSON_H
#define PERSON_H
class Person {
private:
string firstName;
string lastName;
long NID;
public:
Person();
void toString();
string get_firstName() {
    return firstName;
}
string get_lastName() {
    return lastName;
}
long get_NID() {
    return NID;
}
};
#endif

延长人的老师老师

#include "Person.h"
#include <iostream>
#ifndef TEACHER_H
#define TEACHER_H
class Teacher : public Person {
private:
int avg_horarium;
public:
Teacher();
void toString();
int get_avg_horarium() {
    return avg_horarium;
}
};
#endif

然后是老师。cpp:

#include "Teacher.h"
using namespace std;
Teacher::Teacher() : Person() {
cout << "Enter average monthly horarium: ";
cin >> avg_horarium;
}
void Teacher::toString() {
Person::toString();
cout << "Average monthly horarium: " << avg_horarium;
}

另一个扩展人的班级是学生,因为它与老师相似,所以我不会在这里发布。我的问题是,在屏幕截图上获取所有这些错误,我做错了什么:http://s14.postimage.org/45k08ckb3/errors.jpg

问题是您对stdafx.h文件的不正确处理。在MSVC编译器中,当启用预编译标头时,#include "stdafx.h"行之前的所有内容都被忽略。

首先,停止将stdafx.h加入标头(.h)文件。stdafx.h应该包含在实现(.cpp)文件中。在您的情况下,#include "stdafx.h"应放入Person.cppTeacher.cpp中,而不是Person.hTeacher.h

其次,要么禁用项目中的预编译标头,要么确保#include "stdafx.h"始终是您每个实现文件中最有意义的行。所有其他#include指令均应在 #include "stdafx.h"之后进行,而不是之前。

在您的标题文件放置;

 #ifndef CLASSNAME_H
 #define CLASSNAME_H

在文件的顶部,在include语句之后,在班级声明之前。放

#endif

在所有代码之后,在文件的底部。这样可以确保仅定义课程一次。具有相同标头文件的多个包含多个,通常会导致链接问题。

刚刚放入标题a Guard

#ifndef _THIS_FILENAME
#define _THIS_FILENAME
wibble etc

#endif

编辑

忘了提及使用前瞻性声明 - 节省了重新编译的费用。