C++中多态、虚函数、抽象函数的用法
一、学习要点:
1.多态的关键条件,不光要因为因为对象不同,调用同一函数,实现不同的功能,最重要的一点,还有父类引用子类对象.
#include
#include
using namespace std;
class A{
public:void print();
};
void A::print(){cout<<"this is A"<class B:public A{
public:void print();
};
void B::print(){cout<<"this is B"<int main(){A a;B b;a.print();b.print();system("pause");return 0;
}
执行结果
虽然结果实现了多态,但由于源代码并没有体现出父类引用,子类对象,并不能严格的来说是一个多态的实现.
现对代码进行修改:
#include
#include
using namespace std;
class A{
public:void print();
};
void A::print(){cout<<"this is A"<class B:public A{
public:void print();
};
void B::print(){cout<<"this is B"<int main(){A a;B b;A* p1=new A;//父类引用,子类对象A* p2=new B;//父类引用,子类对象p1->print();p2->print();system("pause");return 0;
}
运行结果:
从运行结果上来看,虽然满足多态的条件,但执行结果并没有实现多态.
那么解决这个问题就用到虚函数:
虚函数格式,只需在函数前加上关键字virtual即可.如下对代码进行修改:
#include
#include
using namespace std;
class A{
public:virtual void print();//声明为虚函数
};
void A::print(){cout<<"this is A"<class B:public A{
public:void print();
};
void B::print(){cout<<"this is B"<int main(){A a;B b;A* p1=new A;A* p2=new B;p1->print();p2->print();system("pause");return 0;
}
运行结果如下:实现多态
虚函数总结:
在实现多态的时候,不仅要有父类引用子类对象,还要有虚函数,我们只需把基类函数声明设为virtual,其派生类的相应函数也会成为虚函数。不需要在基类函数定义和派生类函数声明前再加关键字virtual.
纯虚函数也就是抽象函数,抽象函数所在的类为抽象类,只是一个特殊的类,为子类提供接口,抽象类无法实例化,只能通过继承机制,生成抽象类的非抽象派生类,再实例化。
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
