C++ 纯虚函数和抽象类

纯虚函数是一种特殊的虚函数,它的一般格
式如下:

class <类名>
{
virtual<类型><函数名>(<参数表>)=0;
}

.. 带有纯虚函数的类称为抽象类
.. 抽象类是不能定义对象的,在实际中为
了强调一个类是抽象类,可将该类的构
造函数声明为保护的控制权限
.. 抽象类只能作为基类来使用,其纯虚函
数的实现由派生类给出。如果派生类中
没有重定义纯虚函数,则这个派生类仍
然还是一个抽象类

//抽象类
#include <iostream>

using std::cin;
using std::cout;
using std::endl;

class Vehicle{  
protected:      
    float speed;
    int   total;     
public:     
    Vehicle(float speed,int total){    
        this->speed = speed;    
        this->total = total;
        cout<<"in Vehicle construct"<<endl;
    }    
    Vehicle(const Vehicle  & vv){
        cout<<"in Vehicle copy"<<endl;
    }

    virtual void ShowMember() = 0;//纯虚函数的定义

    virtual ~Vehicle(){}
};

class Car:public Vehicle{
protected:      
    int aird;   

public:
    Car(int aird,float speed,int total):Vehicle(speed,total){      
        this->aird = aird;    
        cout<<"in car construct"<<endl;
    }
    Car(Car & cc):Vehicle(cc){
        this->aird = cc.aird;
        cout<<"in Car copy "<<endl;
    }

    virtual  void ShowMember(){   //派生类成员函数重载  
        cout<<aird<<"|"<<speed<<"|"<<total<<endl;    
    }   
};      

int main()    
{  
    //Vehicle a(100,4);//错误,抽象类不能创建对象   
    Car b(250,150,4);
    cout<<"========"<<endl;
    Car c = b;
    b.ShowMember();  
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值