1.抽象类概念
做一个"各个国家的人"的调查:饮食、穿衣、开车...
virtual void eating(void) 这些函数没必要在基类里面实现,派生类里面肯定提供这些函数
virtual void eating(void) = 0; 纯虚函数 含有纯虚函数的类 称为抽象类,抽象类不能用来实例化对象,它是用来给派生类定义好框架
#include <iostream>
#include <string.h>
#include <unistd.h>
using namespace std;
class Human {
private:
int a;
public:
virtual void eating(void) = 0;
virtual void wearing(void) = 0;
virtual void driving(void) = 0;
virtual ~Human() { cout<<"~Human()"<<endl; }
virtual Human* test(void) {cout<<"Human's test"<<endl; return this; }
};
class Englishman : public Human {
public:
void eating(void) { cout<<"use knife to eat"<<endl; }
void wearing(void) {cout<<"wear english style"<<endl; }
void driving(void) {cout<<"drive english car"<<endl; }
virtual ~Englishman() { cout<<"~Englishman()"<<endl; }
virtual Englishman* test(void) {cout<<"Englishman's test"<<endl; return this; }
};
class Chinese : public Human {
public:
void eating(void) { cout<<"use chopsticks to eat"<<endl; }
void wearing(void) {cout<<"wear chinese style"<<endl; }
void driving(void) {cout<<"drive chinese car"<<endl; }
virtual ~Chinese() { cout<<"~Chinese()"<<endl; }
virtual Chinese* test(void) {cout<<"Chinese's test"<<endl; return this; }
};
int main(int argc, char **argv)
{
//Human h; err
Englishman e;
Chinese c;
return 0;
}
2. 若子类没有覆写所有的纯虚函数,则子类还是抽象类
#include <iostream>
#include <string.h>
#include <unistd.h>
using namespace std;
class Human {
private:
int a;
public:
virtual void eating(void) = 0;
virtual void wearing(void) = 0;
virtual void driving(void) = 0;
virtual ~Human() { cout<<"~Human()"<<endl; }
virtual Human* test(void) {cout<<"Human's test"<<endl; return this; }
};
class Englishman : public Human {
public:
void eating(void) { cout<<"use knife to eat"<<endl; }
void wearing(void) {cout<<"wear english style"<<endl; }
void driving(void) {cout<<"drive english car"<<endl; }
virtual ~Englishman() { cout<<"~Englishman()"<<endl; }
virtual Englishman* test(void) {cout<<"Englishman's test"<<endl; return this; }
};
class Chinese : public Human {
public:
void eating(void) { cout<<"use chopsticks to eat"<<endl; }
void wearing(void) {cout<<"wear chinese style"<<endl; }
//void driving(void) {cout<<"drive chinese car"<<endl; }
virtual ~Chinese() { cout<<"~Chinese()"<<endl; }
virtual Chinese* test(void) {cout<<"Chinese's test"<<endl; return this; }
};
class Guangximan : public Chinese {
void driving(void) {cout<<"drive guangxi car"<<endl; }
};
int main(int argc, char **argv)
{
//Human h;
Englishman e;
Guangximan g;
return 0;
}
如果Chiness 中没有实现 driving函数,那么 Chiness 还是一个抽象类,不能用来是实例化对象
3.总结
Human:向下定义好框架,向上提供统一的接口