基类与派生类对象之间的转换&拷贝构造&虚析构&赋值操作符
#include <iostream>
#include <string>
using namespace std;
class Item_base
{
private:
string isbn;
protected:
double price;
public:
//构造函数
Item_base(const string &book = "",double sales_price = 0.0):isbn(book),price(sales_price)
{
cout<<"基类的构造函数"<<endl;
}
string book() const
{
return isbn;
}
//虚函数
virtual double net_price(size_t n) const
{
return n*price;
}
//复制构造函数
Item_base(const Item_base& ib):isbn(ib.isbn),price(ib.price)
{
cout<<"基类的复制构造函数"<<endl;
}
//赋值操作符重载
Item_base& operator = (const Item_base& rhs)
{
isbn = rhs.isbn;
price = rhs.price;
cout<<"基类的赋值操作符重载"<<endl;
return *this;
}
//虚析构函数
virtual ~Item_base()
{
cout<<"基类析构函数"<<endl;
}
};
class Bulk_item : public Item_base
{
private:
size_t min_qty;
double discount;
public:
//构造函数
Bulk_item(const string& book = "",double sales_price = 0.0,size_t qty = 0,double disc_rate = 0.0)
:Item_base(book,sales_price),min_qty(qty),discount(disc_rate)
{
cout<<"派生类构造函数"<<endl;
}
double net_price(size_t n) const
{
if (n >= min_qty)
{
return n * (1-discount)*price;
}
else
{
return n * price;
}
}
//复制构造函数
Bulk_item(const Bulk_item& b):Item_base(b),min_qty(b.min_qty),discount(b.discount)
{
cout<<"派生类复制构造函数"<<endl;
}
//赋值重载操作符
Bulk_item& operator = (const Bulk_item& rhs)
{
if (this != &rhs)
{
Item_base::operator=(rhs);
}
min_qty = rhs.min_qty;
discount = rhs.discount;
cout<<"派生类赋值操作符重载"<<endl;
return *this;
}
//虚析构函数
virtual ~Bulk_item()
{
cout<<"派生类析构函数"<<endl;
}
};
void fun1(Item_base obj)//形参为Item_base
{
}
void fun2(Item_base& obj)//形参为Item_base对象的引用
{
}
Item_base fun3()
{
Item_base obj;
return obj;
}
void main()
{
//调用Item_base的普通构造函数,创建Item_base对象iobj
Item_base iobj;
cout<<endl;cout<<endl;
fun1(iobj);
cout<<endl;cout<<endl;
fun2(iobj);
cout<<endl;cout<<endl;
iobj=fun3();
cout<<endl;cout<<endl;
Item_base *p = new Item_base;
cout<<endl;cout<<endl;
delete p;
cout<<endl;cout<<endl;
Bulk_item bobj;
cout<<endl;cout<<endl;
fun1(bobj);
cout<<endl;cout<<endl;
fun2(bobj);
cout<<endl;cout<<endl;
Bulk_item *q = new Bulk_item;
cout<<endl;cout<<endl;
delete q;
}