这里用两段简单的代码来介绍C++的多态公有继承和虚函数的简单用法。
代码片段一:
#include<iostream>
#include<cstring>
#define NAMELENGTH 10
using namespace std;
class Human
{
private:
double m_money;
char m_name[NAMELENGTH];
public:
Human(double money, const char* name):m_money(money)
{
strncpy(m_name, name, NAMELENGTH-1);
m_name[NAMELENGTH-1] = '\0';
}
~Human(){}
void name()
{
cout<<"name is:" << m_name<<endl;
}
char* getname()
{
return m_name;
}
};
class You : public Human
{
public:
You(double money, char* name):Human(money, name){}
~You(){}
void name()
{
cout<<"your name is:"<<Human::getname()<<endl;
}
};
class Me : public Human
{
private:
int cars;
public:
Me(double money, const char* name, int c):Human(money, name),cars(c){}
~Me(){}
void name()
{
cout<<"my name is:"<<Human::getname()<<endl;
cout<<"I have "<<cars<<" cars"<<endl;
}
};
int main(void)
{
Me wuyilun(100000.0, "wuyilun", 100);
<pre name="code" class="html"> wuyilun.name();
Human &who = wuyilun;who.name();Human *who1 = &wuyilun;who1->name();return 0;}
这里定义了一个Human基类以及继承该Human类的Me和You泛类,Me和You都重写了基类Human中的name()函数。其执行结果如下,可检验一下。
Human类指针指向Me对象,执行的name()函数依然是Human类里的name()函数,而不是Me对象的name()函数。可见普通的公有继承并不能实现多态。
代码片段一:(通过对代码片段一的简单修改来对比查看虚函数的用法)
#include<iostream>
#include<cstring>
#define NAMELENGTH 10
using namespace std;
class Human
{
private:
double m_money;
char m_name[NAMELENGTH];
public:
Human(double money, const char* name):m_money(money)
{
strncpy(m_name, name, NAMELENGTH-1);
m_name[NAMELENGTH-1] = '\0';
}
virtual ~Human(){}
virtual void name() {};
char* getname()
{
return m_name;
}
};
class You : public Human
{
public:
You(double money, const char* name):Human(money, name){}
~You(){}
void name()
{
cout<<"your name is:"<<Human::getname()<<endl;
}
};
class Me : public Human
{
private:
int cars;
public:
Me(double money, const char* name, int c):Human(money, name),cars(c){}
~Me(){}
void name()
{
cout<<"my name is:"<<Human::getname()<<endl;
cout<<"I have "<<cars<<" cars"<<endl;
}
};
int main(void)
{
Me wuyilun(100000.0, "wuyilun", 100);
wuyilun.name();
You funny(10.0, "funny guy");
funny.name();
Human *who = &wuyilun;
who->name();
who = &funny;
who->name();
return 0;
}
把基类Human中的name()方法变成虚函数,然后在main()函数中通过Human类指针指向Me对象和You对象,调用其name()函数,对比一下和代码片段一的区别。
下面是该代码片段的执行结果。