#include<iostream>
using namespace std;
class Item_base
{
public:
Item_base( const string &book=" ni",double sales_price=0.0):isbn(book),price(sales_price){cout<<"构造函数执行"<<endl;}
string book() const//必须加const或者会出现错误'book' : cannot convert 'this' pointer from 'const class Item_base' to 'class Item_base &'
{
return isbn;
}
virtual double net_price(size_t n)const
{
return n*price;
}
virtual ~Item_base(){cout<<"析构函数执行"<<endl;}
private:
string isbn;
protected:
double price;
};
class Bulk_item:public Item_base
{
public:
double net_price(size_t)const;
private:
size_t min_qty;
double discount;
};
double Bulk_item::net_price(size_t cnt)const
{
if(cnt>=min_qty)
return cnt*(1-discount)*price;
else
return cnt*price;
}
void print_total(ostream &os, const Item_base &item,size_t n)
{
os<<"ISBN:"<<item.book()<<"\tnumber sold: "<<n<<"\ttotal price:"<<item.net_price(n)<<endl;
}
int main()
{
Item_base A;
Bulk_item B;
print_total(cout,A,10);
print_total(cout,B,10);
}
这个程序需要加#include<string>或者会出现编译错误因为要用到 string类 要不然会出现binary '<<' : no operator defined which takes a right-hand operand of type 'class std::basic_string<char,struct std::char_traits<c这样的错误
(2)有关const问题 在book ()函数后面要加上const 或者会出现