码迷,mamicode.com
首页 > 编程语言 > 详细

C++ 纯虚函数

时间:2020-02-20 17:14:41      阅读:57      评论:0      收藏:0      [点我收藏+]

标签:iostream   clu   col   pac   vector   color   函数   void   this   

#include <iostream>
#include <vector>
using namespace std;


class reslut
{
public:
    reslut()
    {
    }
    int get_a()
    {
        return a;
    }
    int get_b()
    {
        return b;
    }
    void set_a(int x)
    {
        this->a = x;

    }
    void set_b(int y)
    {
        this->b = y;

    }
    ~reslut()
    {
    }
    virtual int test() = 0;
  
protected:
    int  a;
    int  b;
};


class AA : public reslut  
{
public:
    int test()   //重写父类的纯虚函数
    {
        return a + b;
    }

};

class BB :public reslut
{
public:
    int test()  //重写父类的纯虚函数
    {
        return a*b;
    }

};

int main()
{
    AA test1;
    
    test1.set_a(1);
    test1.set_b(2);
   int reslut1= test1.test(); 

    BB test2;

    test2.set_a(1);
    test2.set_b(2);
    int reslut2 = test2.test();

    return 0;
}

 当类中有纯虚函数时,该类无法被实例话,只能通过子类继承,并重写该纯虚函数时,该类中的其他函数以及成员才可以通过实例化子类后,使用父类的成员以及函数

C++ 纯虚函数

标签:iostream   clu   col   pac   vector   color   函数   void   this   

原文地址:https://www.cnblogs.com/shenji/p/12336217.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!