______________________________________________________________Human.h_________________________________________________________________________________________________________________________
public:
Human(void);
Human(const Human &Other);
~Human(void);
void sleep(void);
virtual void eat(void);
}; ________________________________________________________________Human.cpp___________________________________________________________
//在源文件中,包含Human類的函數實現
#include"Human.h"Human::Human(void) {}
Human::Human(const Human &other){}
Human::~Human(void){}
void Human::sleep(void){}
void Human::eat(void)
{
std::cout<<"Human::eat(void)"<<std::endl;
}
__________________________________________________________________Man.h_____________________________________________________________
#include"Human.h"class Man:public Human
{
public:
void eat(void);
};
_________________________________________________________________Man.cpp____________________________________________________________
#include"Man.h"
void Man::eat(void)
{
std::cout<<"Man::eat(void)"<<std::endl;
}
____________________________________________________________Main.cpp_________________________________________________________________
#include"Human.h"#include"Man.h"
void Function(Human * P_Human)
{
P_Human->eat();
}
int main()
{
Human human1, *human2;
human2 = &human1;
Man man;
Function(human2);
Function(&man);
system("pause");
return 0;
}
在這種情況下編譯會出現錯誤,是因爲在Main.cpp源文件中,已經包含了Human.h頭文件(Human類的定義),錯誤出在:#include<Man.h>,因爲其中包括了類Human的定義,導致再次定義類(重複定義)。
———————————————————————————————————————————————————————————————————————————————————————————————————————————————
改正錯誤只需要將Human.h頭文件改爲以下代碼:
#ifndef _HUMAN_H
#define _HUMAN_H
#include<iostream>
class Human
{
public:
Human(void);
Human(const Human &Other);
~Human(void);
void sleep(void);
virtual void eat(void);
};
#endif
以上代碼在vs2008上編譯通過,希望能你能親自試試看!!!加深印象,有錯誤希望指正!!哪裏不明白請留言,儘量幫助你解決!!
祝好!