c++的多态性
#include <iostream>using namespace std;/*c++多态性当c++编译器在编译的时候,发现Animal类的breath()函数是虚函数,这个时候c++就会采用迟绑定技术也就是编译时并不确定具体调用的函数,而且在运行时候,依据对象的类型(在程序中,我们传递的fish类对象的地址)来确认调用的是哪一个函数,这种能力就叫做c++的多态性c+
·
#include <iostream>
using namespace std;
/*
c++多态性
当c++编译器在编译的时候,发现Animal类的breath()函数是虚函数,这个时候c++就会采用迟绑定技术
也就是编译时并不确定具体调用的函数,而且在运行时候,依据对象的类型(在程序中,我们传递的fish类对象的地址)
来确认调用的是哪一个函数,这种能力就叫做c++的多态性
c++的多态性用一句话概括:在基类的函数前加上virtual关键字,在派生类中重写该函数,运行时
将会根据对象的实际类型来调用相应的函数
如果对象类型是派生类,就调用派生类的函数,如果对象类型是基类,就调用基类的函数
*/
class Animal
{
public:
Animal(int height,int weight)
{
cout << "Animal construct" << endl;
}
~Animal()
{
cout << "Animal destruct" << endl;
}
void eat()
{
cout << "Animal eat " << endl;
}
void sleep()
{
cout << "Animal sleep " << endl;
}
virtual void breathe()
{
cout << "Animal breathe " << endl;
}
};
class fish:public Animal
{
public:
void breathe()
{
cout << "fish bubble " << endl;
}
fish() :Animal(400,300)
{
cout << "fish construct" << endl;
}
~fish()
{
cout << "fish destruct" << endl;
}
};
void fn(Animal *pAn)
{
pAn->breathe();
}
int main()
{
fish f1;
fn(&f1);
return 0;
}
/*
纯虚函数是指被表明不具体实现的虚成员函数
纯虚函数可以让类先具有一个操作名称,而没有操作内容
让派生类在继承时再去具体给出定义 凡是含有纯虚函数的类叫做抽象类
这种类不能声明对象,只是作为基类为派生类服务,在派生类中必须完全实现基类的纯虚函数
否则派生类变成抽象类,不能实例化对象
c++的多态性是由虚函数实现的,而不是纯虚函数
在子类中如果有对基类虚函数的覆盖定义,无论覆盖定义是否有virtualg
*/
class animal
{
public:
void eat()
{
cout << "animal eat" << endl;
}
void sleep()
{
cout << "animal sleep" << endl;
}
virtual void breathe() = 0;
};
#include <iostream>
using namespace std;
/*
函数的覆盖是发生在派生类与基类之间,两个函数必须完全相同,并且都是虚函数
不属于这种情况,就是隐藏
*/
class Base
{
public:
virtual void xfn(int i)
{
cout << "Base::xfn(int i)" << endl;
}
void yfn(float f)
{
cout << "Base::yfn(float f)" << endl;
}
void zfn()
{
cout << "Base::zfn()" << endl;
}
};
class Derived :public Base
{
public:
void xfn(int i)//1.两个都是虚函数2.两个函数完全相同
{
cout << "Derived::xfn(int i)" << endl;
}
void yfn(int c)//两个都不是虚函数,函数还不相同,属于函数隐藏
{
cout << "Derived::yfn(int c)" << endl;
}
void zfn()//两个函数都不是虚函数,函数相同,属于函数隐藏
{
cout << "Derived::zfn()" << endl;
}
};
void main()
{
Derived d;
Base *pB = &d;
Derived *pD = &d;
pB->xfn(5);
pD->xfn(5);
pB->yfn(3.14f);
pD->yfn(3.14f);
pB->zfn();
pD->zfn();
}
更多推荐
已为社区贡献2条内容
所有评论(0)