抽象类

来源:互联网 发布:荆门网络作文大赛 编辑:程序博客网 时间:2024/05/16 02:05

1.纯虚函数

  在基类中仅仅给出声明,不对虚函数实现定义,而是在派生类中实现。这个虚函数称为纯虚函数。普通函数如果仅仅给出它的声明而没有实现它的函数体,这是编译不过的。纯虚函数没有函数体。

  纯虚函数需要在声明之后加个=0

class <基类名>

{

virtual <类型><函数名>(<参数表>)=0; ......

};

2.抽象类

  含有纯虚函数的类被称为抽象类。抽象类只能作为派生类的基类,不能定义对象,但可以定义指针。在派生类实现该纯虚函数后,定义抽象类对象的指针,并指向或引用子类对象。

1)在定义纯虚函数时,不能定义虚函数的实现部分;

2)在没有重新定义这种纯虚函数之前,是不能调用这种函数的。

  抽象类的唯一用途是为派生类提供基类,纯虚函数的作用是作为派生类中的成员函数的基础,并实现动态多态性。继承于抽象类的派生类如果不能实现基类中所有的纯虚函数,那么这个派生类也就成了抽象类。因为它继承了基类的抽象函数,只要含有纯虚函数的类就是抽象类。纯虚函数已经在抽象类中定义了这个方法的声明,其它类中只能按照这个接口去实现。

抽象类实例:

#define _CRT_SECURE_NO_WARNINGS#include <iostream>#include <cstring>using namespace std;class abstractFather{ /*定义抽象类*/public:virtual int GetValue() = 0;/*纯虚函数*/};class abstractChild1 :public abstractFather{public:abstractChild1(int a, int b, int c){this->m_a = a;this->m_b = b;this->m_c = c;}int GetValue(){return (m_a*m_b*m_c);}private:int m_a;int m_b;int m_c;};class abstractChild2 :public abstractFather{public:abstractChild2(int a, int b){this->m_a = a;this->m_b = b;}int GetValue(){return (m_a*m_b*2);}private:int m_a;int m_b;};class abstractChild3 :public abstractFather{public:abstractChild3(int a){this->m_a = a;}int GetValue(){return (m_a*m_a+2*m_a);}private:int m_a;int m_b;};int stage(abstractFather* oop){return (oop->GetValue());}int main(){abstractChild1 oop1(1, 2, 3);cout << "oop1:  " << stage(&oop1) << endl;abstractChild2 oop2(4, 5);cout << "oop2:  " << stage(&oop2) << endl;abstractChild3 oop3(10);cout << "oop3:  " << stage(&oop3) << endl;system("pause");return 0;}



原创粉丝点击