重载(overload):同一个类中,函数名字相同,参数不同(参数类型和个数),virtual可有可无(返回值这个条件不构成重载)
覆盖(override,重写):子类函数覆盖父类函数,函数名字相同,参数相同,基类函数必须有virtual关键字,子类virtual可有可无
隐藏:子类函数把父类函数隐藏,函数名字相同,参数不同,virtual可有可无
子类函数把父类函数隐藏,函数名字相同,参数相同,基类函数没有virtual关键字
class Animal
{
public:
Animal():m_name("animal"),m_sex('M'),m_age(1)
{
}
virtual ~Animal()
{
}
//函数重载
void show()
{
cout << "Animal show()" << endl;
}
void show(int var)
{
cout << "Animal show():" << var << endl;
}
// int show()//错误写法
// {
// return 0;
// }
//虚函数
virtual void print()
{
cout << "Animal---";
cout << "name:" << m_name << " sex:" << m_sex << " age:" << m_age << endl;
}
//普通函数
void eat()
{
cout << "Animal eat()" << endl;
}
void doNothing()
{
cout << "Animal doNothing()" << endl;
}
void fun()
{
cout << "Animal fun()" << endl;
}
protected:
string m_name;
char m_sex;
int m_age;
};
class Lion:public Animal
{
public:
Lion():Animal(),m_weight(100)
{
}
~Lion()
{
}
//覆盖父类的print,同名函数,参数一样,返回值一样,父类有virtual关键字
void print()
{
cout << "Lion---";
cout << "name:" << m_name << " sex:" << m_sex << " age:" << m_age
<< " weight:" << m_weight << endl;
}
//隐藏父类的print
void print(int var)
{
cout << "Lion---";
cout << "name:" << m_name << " sex:" << m_sex << " age:" << m_age
<< " weight:" << m_weight
<< " var:" << var << endl;
}
// int print()//错误写法
// {
// return 0;
// }
//同名函数,参数一样,返回值一样,隐藏父类的eat
void eat()
{
cout << "Lion eat()" << endl;
}
//同名函数,参数不一样,返回值一样,隐藏父类的doNothing
void doNothing(int var)
{
cout << "Lion doNothing():" << var << endl;
}
//同名函数,参数一样,返回值不一样,应该也算隐藏?
int fun()
{
cout << "Lion fun()" << endl;
return 1;
}
private:
float m_weight;
};
int main(int argc, char *argv[])
{
Animal a;
Lion l;
//重载:同一个类中,函数名字相同,参数不同(参数类型和个数),virtual可有可无(返回值这个条件不构成重载)
a.show();
a.show(2);
//覆盖(重写):子类函数覆盖父类函数,函数名字相同,参数相同,基类函数必须有virtual关键字,子类virtual可有可无
l.print();
//隐藏:子类函数把父类函数隐藏,函数名字相同,参数不同,virtual可有可无
//子类函数把父类函数隐藏,函数名字相同,参数相同,基类函数没有virtual关键字
l.print(9);
l.eat();
//l.doNothing();//此处不能调用了,被隐藏了
l.doNothing(2);
l.fun();
//用父类的指针调用情况
cout << "----------------------------------" << endl;
Animal *p = &a;//指向父类的对象
p->show();
p->show(2);
p->print();
//p->print(9);//编译通不过
p->eat();
p->doNothing();
//p->doNothing(2);//编译通不过
p->fun();
cout << "----------------------------------" << endl;
p = &l;//指向子类的对象
p->show();
p->show(2);
p->print();//动态联编
//p->print(9);//编译通不过
p->eat();
p->doNothing();
//p->doNothing(2);//编译通不过
p->fun();
return 0;
}
深入了解