1.纯虚函数的定义:
纯虚函数可以让类先具有一个操作名称,而没有操作内容,让派生类在继承时再去具体地给出定义。凡是含有纯虚函数的类叫做抽象类。这种类不能声明对象,只是作为基类为派生类服务。除非在派生类中完全实现基类中所有的的纯虚函数,否则,派生类也变成了抽象类,不能实例化对象。
2.引入纯虚函数的原因
1、为了方便使用
多态特性,我们常常需要在基类中定义虚函数。
2、在很多情况下,基类本身生成对象是不合情理的。例如,动物作为一个基类可以派生出老虎、孔雀等子类,但动物本身生成对象明显不合常理。
为了解决上述问题,引入了纯虚函数的概念,将函数定义为纯虚函数(方法:virtual ReturnType Function()= 0;)。若要使派生类为非抽象类,则编译器要求在派生类中,必须对纯虚函数予以重写以实现多态性。同时含有纯虚函数的类称为抽象类,它不能生成对象。这样就很好地解决了上述两个问题。
3.相似的概念
多态性:
b运行时
多态性:通过虚函数实现。
//
// 纯虚函数
//
///
#include <iostream>
#include <string>
using namespace std ;
// 基类
class Item_Base
{
public:
// 默认构造函数
Item_Base( const string& book = "" , double sales_price = 0.0 ) : isbn( book ) , price( sales_price ) { }
// 拷贝构造函数
Item_Base( const Item_Base& item ) : isbn( item.isbn ) , price( item.price )
{
}
// 重载赋值操作符
Item_Base& operator= ( const Item_Base& item )
{
isbn = item.isbn ;
price = item.price ;
return *this ;
}
string book() const { return isbn ; }
virtual double net_price( int n ) const
{
return n * price ;
}
virtual ~Item_Base() { }
private:
string isbn ;
public:
double price ;
} ;
// 派生类
class Bulk_Item : public Item_Base
{
public:
// 构造函数
Bulk_Item ( const string& book , double sales_price , int qty = 0 , double discount_rate = 0.0 )
: Item_Base( book , sales_price ) , min_qty( qty ) , discount( discount_rate ) { }
// 默认构造函数
Bulk_Item() { }
// 拷贝构造函数
Bulk_Item( const Bulk_Item& item ) : Item_Base( item ) , min_qty( item.min_qty ) , discount( item.discount )
{
}
// 重载赋值操作符
Bulk_Item& operator= ( const Bulk_Item& rhs )
{
if( this != &rhs )
{
Item_Base::operator =( rhs ) ;
min_qty = rhs.min_qty ;
discount = rhs.discount ;
}
return *this ;
}
double net_price( int n ) const ;
private:
int min_qty ;
double discount ;
} ;
double Bulk_Item::net_price( int n ) const
{
if( n >= min_qty )
{
return n * price * ( 1 - discount ) ;
}
else
{
return n * price ;
}
}
void print_total( ostream& os , const Item_Base& item , int n )
{
os << "ISBN: " << item.book()
<< "\nnumber_sold: " << n << "\ntotal_price: "
<< item.net_price( n ) << endl ;
}
int main()
{
Item_Base base( "123456" , 1.2 ) ;
Bulk_Item derived( "123456" , 1.2 , 5 , 0.5 ) ;
print_total( cout , base , 10 ) ;
cout << endl ;
print_total( cout , derived , 10 ) ;
cout << endl ;
Item_Base temp1 = base ; // 调用复制构造函数
Bulk_Item temp2 = derived ; // 调用复制构造函数
print_total( cout , base , 10 ) ;
cout << endl ;
print_total( cout , derived , 10 ) ;
cout << endl ;
Item_Base temp_base ;
temp_base = base ; // 复制,调用复制操作符
Bulk_Item temp_bulk ;
temp_bulk = derived ; // 复制,调用复制操作符
print_total( cout , temp_base , 10 ) ;
cout << endl ;
print_total( cout , temp_bulk , 10 ) ;
return 0 ;
}