[英]Base class undefined error in C++
- -更新 - -
我在项目中包含头文件和 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
扩展 Person Teacher.h 的教师
#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
然后是Teacher.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;
}
另一个扩展 Person 的类是 Student ,因为它与老师相似,所以我不会在这里发布它。 我的问题是我做错了什么才能在屏幕截图上显示所有这些错误: http : //s14.postimage.org/45k08ckb3/errors.jpg
问题是你对stdafx.h
文件的错误处理。 在 MSVC 编译器中,当启用预编译头时, #include "stdafx.h"
行之前的所有内容都将被忽略。
首先,停止将stdafx.h
包含到头文件 ( .h
) 中。 stdafx.h
应该包含在实现 ( .cpp
) 文件中。 在您的情况下, #include "stdafx.h"
应该放入Person.cpp
和Teacher.cpp
,而不是放入Person.h
和Teacher.h
。
其次,要么禁用项目中的预编译头,要么确保#include "stdafx.h"
始终是每个实现文件中第一个有意义的行。 所有其他#include
指令应该在#include "stdafx.h"
,而不是之前。
在你的头文件中放;
#ifndef CLASSNAME_H
#define CLASSNAME_H
在文件的顶部,在include
语句之后,在类声明之前。 放
#endif
在所有代码之后的文件底部。 这确保类只定义一次。 对同一个头文件有多个包含通常会导致链接问题。
只需将一名后卫放入头球
IE
#ifndef _THIS_FILENAME
#define _THIS_FILENAME
wibble etc
#endif
编辑
忘记提及使用前向声明 - 节省重新编译的费用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.