1、
做一个“各个国家的人”的调查,饮食,穿衣,开车。。。
当一个函数,前面加上virtual,后面加上 = 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()
{
cout<<"use knife to eat"<<endl;
}
void wearing(void)
{
cout<<"wearing 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()
{
cout<<"use chopsticks to eat"<<endl;
}
void wearing(void)
{
cout<<"wearing 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; //error 抽象类不能用来实例化对象
Englishman e;
Chinese c;
return 0;
}
Human:向下定义好框架,向上提供统一的接口,应用程序可以根据这个统一的函数来操作一个人
Englishman
Chinese
派生类必须实现纯虚函数,抽象类不能够实例化对象,也就是说我们定义一个人的时候要么用英国人,要么用中国人,要么用其他国家的人,但是不能够直接使用Human来定义一个人。
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()
{
cout<<"use knife to eat"<<endl;
}
void wearing(void)
{
cout<<"wearing 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()
{
cout<<"use chopsticks to eat"<<endl;
}
void wearing(void)
{
cout<<"wearing 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)
{
Englishman e;
Chinese c; // error 编译会出错
Guangximan c;
return 0;
}