抽象:
纯虚函数:
1.virtual函数声明时后面加上 "=0";
2.纯虚函数不需要定义
3.所有的纯虚函数都需要复写
1 #include <iostream> 2 #include <string.h> 3 #include <unistd.h> 4 5 using namespace std; 6 7 class Human{ 8 private: 9 int a; 10 public: 11 virtual void eating(void) = 0; 12 virtual void wearing(void) = 0; 13 virtual void driving(void) = 0; 14 virtual ~Human() {cout <<"~Human()"<<endl;} 15 virtual Human *test (void){cout<<"Human's test"<<endl;return this;} 16 17 }; 18 class Englishman : public Human{ 19 public: 20 void eating(void){cout<<"use knife to eat"<<endl;} 21 void wearing(void){cout<<"wear english style"<<endl;} 22 void driving(void){cout<<"drive english car"<<endl;} 23 virtual ~Englishman(){cout<<"~Englishman()"<<endl;} 24 virtual Englishman* test(void){cout<<"Englishman's test"<<endl;return this;} 25 26 27 }; 28 class Chinese : public Human{ 29 public: 30 void eating(void){cout<<"use chopsticks to eat"<<endl;} 31 void wearing(void){cout<<"wear chinese style"<<endl;} 32 //void driving(void){cout<<"drive chinese car"<<endl;} 33 virtual ~Chinese(){cout<<"~Chinese()"<<endl;} 34 virtual Chinese* test(void){cout<<"Chinese's test"<<endl;return this;} 35 36 }; 37 class Guangximan : public Chinese{ 38 //void driving(void){cout<<"drive chinese car"<<endl;} 39 }; 40 int main(int argc,char ** argv) 41 { 42 Englishman e; 43 Chinese c; 44 45 return 0; 46 }
1 #include <iostream> 2 #include <string.h> 3 #include <unistd.h> 4 5 using namespace std; 6 7 class Human{ 8 private: 9 int a; 10 public: 11 virtual void eating(void) = 0; 12 virtual void wearing(void) = 0; 13 virtual void driving(void) = 0; 14 virtual ~Human() {cout <<"~Human()"<<endl;} 15 virtual Human *test (void){cout<<"Human's test"<<endl;return this;} 16 17 }; 18 class Englishman : public Human{ 19 public: 20 void eating(void){cout<<"use knife to eat"<<endl;} 21 void wearing(void){cout<<"wear english style"<<endl;} 22 void driving(void){cout<<"drive english car"<<endl;} 23 virtual ~Englishman(){cout<<"~Englishman()"<<endl;} 24 virtual Englishman* test(void){cout<<"Englishman's test"<<endl;return this;} 25 26 27 }; 28 class Chinese : public Human{ 29 public: 30 void eating(void){cout<<"use chopsticks to eat"<<endl;} 31 void wearing(void){cout<<"wear chinese style"<<endl;} 32 void driving(void){cout<<"drive chinese car"<<endl;} 33 virtual ~Chinese(){cout<<"~Chinese()"<<endl;} 34 virtual Chinese* test(void){cout<<"Chinese's test"<<endl;return this;} 35 36 }; 37 int main(int argc,char ** argv) 38 { 39 Englishman e; 40 Chinese c; 41 42 return 0; 43 }
此代码运行结果为下图:
抽象类:
1.含有纯虚函数的类
2.抽象类不能有实例对象
3.若子类没有覆写所有的纯虚函数,则子类还是抽象类
抽象类界面: