#include <iostream>
#include <string.h>
using namespace std;
//定义个test类
class test
{
private:
char id[20];
public:
//test构造函数
test(const char *idn)
{
strcpy(id,idn);
}
//test成员函数,用来获取数据
char *getid(void)
{
return id;
}
};
//定义个father类
class father
{
private:
char name[20];
test id;//数据成员中包含一个test类
public:
//father的构造函数,无返回值,void也不行
father(const char *n,const char *i);
void setName(const char *);
char *getName(void);
char *getId(void);
// 前面加上virtual代表是个虚函数
virtual void show(void);
};
//father类的show()函数
void father::show(void)
{
cout<<"father------>"<<name<<"id"<<id.getid()<<endl;
}
//调用成员数据id的函数获取数据
char *father::getId(void)
{
return id.getid();
}
//father的构造函数,在构造函数后面加上冒号“:”,以及成员数据的名字,
//用了在构造函数中为数据成员id类的构造函数传参数(char *i)
father::father(const char *n,const char *i):id(i)
{
strcpy(name,n);
}
void father::setName(const char *buf)
{
strcpy(name,(char *)buf);
}
char *father::getName(void)
{
return name;
}
//子类child 公有继承(public)father类
//即包含father类的所有信息,但不能访问father类的私有成员
//只能访问father类的公有成员和保护成员(protected)
class child:public father
{
public:
void show(void);//child类的show()函数
child(const char *n,const char *i);
};
//child类的构造函数,为father类传递参数,
//写法与为数据成员类传参相同
child::child(const char *n,const char *i):father(n,i)
{
}
//child类的show()
void child::show(void)
{
cout<< "child----->>"<<"name :"<<getName()<<"id :"<<getId()<<endl;
}
//func函数参数为指向father类的指针
void func(father *p)
{
p->show();
}
int main()
{
child s("xiaoming","1001");
//虽然s为子类,继承了father类的show函数,
//但此时s.show()调用的为子类成员函数
s.show();
//如果想要调用father类的show()函数需要声明
s.father::show();
father p("xiaohong","1001");
//&p为指向father类的指针,则此时执行father类的show()函数
func(&p);
func(&s);//&s为指向child类的指针,
//但func()函数仍然可以执行,此时执行child类
//的show()函数,两种不同的执行方式为多态,而且
//说明子类也是一种父类,可以执行参数为父类的函数
return 0;
}
在上面的func函数中,如果father类的`show()函数没有virtual,则father指针的函数只能执行father的show()函数,加上virtual后,调用的函数根据参数的具体对象执行不同的函数。
如果类中成员函数中virtual后=0,代表类为纯虚类,则这个成员函数可以不实现,如果父类中没有实现,子类继承后子类也是纯虚类