簡體   English   中英

C++ 中的基類未定義錯誤

[英]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.cppTeacher.cpp ,而不是放入Person.hTeacher.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM