我創建了 3 個班級 - GrandMother、Mother 和 Daughter。我寫了一個代碼,使得 Daughter 類繼承自 Mother 類,而 Mother 類繼承自 GrandMother 類。
GrandMother.h :-
#ifndef GRANDMOTHER_H
#define GRANDMOTHER_H
class GrandMother
{
public:
GrandMother();
~GrandMother();
};
#endif // GRANDMOTHER_H
媽媽.h :-
#ifndef MOTHER_H
#define MOTHER_H
class Mother: public GrandMother
{
public:
Mother();
~Mother();
};
#endif // MOTHER_H
女兒.h :-
#ifndef DAUGHTER_H
#define DAUGHTER_H
class Daughter: public Mother
{
public:
Daughter();
~Daughter();
};
#endif // DAUGHTER_H
GrandMother.cpp :-
#include<iostream>
#include "Mother.h"
#include "Daughter.h"
#include "GrandMother.h"
using namespace std;
GrandMother::GrandMother()
{
cout << "Grand Mother Constructor!!" << endl;
}
GrandMother::~GrandMother()
{
cout << "Grand Mother Deconstroctor" << endl;
}
媽媽.cpp :-
#include<iostream>
#include "Mother.h"
#include "Daughter.h"
#include "GrandMother.h"
using namespace std;
Mother::Mother()
{
cout << "Mother Constructor!!" << endl;
}
Mother::~Mother()
{
cout << "Mother Deconstroctor" << endl;
}
女兒.cpp:-
#include<iostream>
#include "Mother.h"
#include "Daughter.h"
#include "GrandMother.h"
using namespace std;
Daughter::Daughter()
{
cout << "Daughter Constructor!!" << endl;
}
Daughter::~Daughter()
{
cout << "Daughter Deconstroctor" << endl;
}
main.cpp :-
#include<iostream>
#include "Mother.h"
#include "Daughter.h"
#include "GrandMother.h"
using namespace std;
int main(){
//GrandMother granny;
//Mother mom;
Daughter baby;
}
當我運行代碼時,它給了我以下錯誤:-
error: expected class-name before '{' token
誰能告訴我我的代碼的哪一部分是錯誤的。
uj5u.com熱心網友回復:
您的標題不是獨立的,因此您必須按正確的順序包含它們:
#include "GrandMother.h"
#include "Mother.h"
#include "Daughter.h"
但它很脆弱。
正確的方法是使標題自包含:
#ifndef GRANDMOTHER_H
#define GRANDMOTHER_H
class GrandMother
{
public:
GrandMother();
~GrandMother();
};
#endif // GRANDMOTHER_H
#ifndef MOTHER_H
#define MOTHER_H
#include "GrandMother.h"
class Mother: public GrandMother
{
public:
Mother();
~Mother();
};
#endif // MOTHER_H
#ifndef DAUGHTER_H
#define DAUGHTER_H
#include "Mother.h"
class Daughter: public Mother
{
public:
Daughter();
~Daughter();
};
#endif // DAUGHTER_H
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/314622.html
