Я тестирую этот учебник по наследованию в разных файлах .h и .cpp.Наследование - разные файлы (C++)
Я сделал необходимые файлы заголовков #include
. Я не мог понять, что не так с кодом, когда я пытаюсь запустить его. Это есть ошибка о том, что:
Тяжесть Code Line Описание проекта Файл
Error C2011 'Person': 'class' type redefinition
Error C2027 use of undefined type 'Person'
Error C2065 'idNum': undeclared identifier
Error C2065 'lastName': undeclared identifier
Error C2065 'firstName': undeclared identifier
Error C2027 use of undefined type 'Person'
Error C2065 'idNum': undeclared identifier
Error C2065 'firstName': undeclared identifier
Error C2065 'lastName': undeclared identifier
ниже мой код:
Person.h
#include <iostream>
#include <string>
using namespace std;
class Person {
private:
int idNum;
string lastName;
string firstName;
public:
void setFields(int, string, string);
void outputData();
};
void Person::setFields(int num, string last, string first) {
idNum = num;
lastName = last;
firstName = first;
}
void Person::outputData()
{
cout << "ID #" << idNum << " Name: " << firstName << " " << lastName << endl;
}
customer.h
#include <iostream>
#include <string>
#include "Person.h"
using namespace std;
class Customer :public Person
{
private:
double balanceDue;
public:
void setBalDue(double);
void outputBalDue();
};
void Customer::setBalDue(double bal) {
balanceDue = bal;
}
void Customer::outputBalDue() {
cout << "Balance due $ " << balanceDue << endl;
}
main.cpp
#include <iostream>
#include <string>
#include "Customer.h"
#include "Person.h"
using namespace std;
int main() {
Customer cust;
//cust.setFields(215, "Santini", "Linda");
//cust.outputData();
cust.setBalDue(147.95);
cust.outputBalDue();
return 0;
}
Edit: Person.h определения
#include <iostream>
#include <string>
#ifndef PERSON_H
#define PERSON_H
using namespace std;
class Person {
private:
int idNum;
string lastName;
string firstName;
public:
void setFields(int, string, string);
void outputData();
};
void Person::setFields(int num, string last, string first) {
idNum = num;
lastName = last;
firstName = first;
}
void Person::outputData()
{
cout << "ID #" << idNum << " Name: " << firstName << " " << lastName << endl;
}
#endif
поиск: заголовок включают охрану – user463035818
Читайте о [* включают охрану *] (https: //en.wikipedia .org/вики/Include_guard). –
Тогда не надо * определять * функции в заголовочных файлах, если вы не помечаете их как 'inline' (явно или неявно). –