//Sale.h
#ifndef SALE_H
#define SALE_H
namespace SYJ
{
class Sale
{
public:
Sale();
Sale(double thePrice);
double getPrice() const;
void setPrice(double newPrice);
virtual double bill() const;
double savings(const Sale& other) const;
friend bool operator <(const Sale& first, const Sale& second);
private:
double price;
};
//bool operator <(const Sale& first, const Sale& second);
} //SYJ
#endif //SALE_H
//Sale.cpp
#include "stdafx.h"
#include <iostream>
#include "Sale.h"
using std::cout;
namespace SYJ
{
Sale::Sale() : price(0)
{}
Sale::Sale(double thePrice)
{
if(thePrice >= 0)
price = thePrice;
else
{
cout <<"Error: Cannot have a negative price!\n";
exit(1);
}
}
double Sale::bill() const
{
return price;
}
double Sale::getPrice() const
{
return price;
}
void Sale::setPrice(double newPrice)
{
if(newPrice >= 0)
price = newPrice;
else
{
cout <<"Error: Cannot have a negative price!\n";
exit(1);
}
}
double Sale::savings(const Sale& other) const
{
return (bill() - other.bill() );
}
bool operator <(Sale& first, Sale& second)
{
return (first.bill() < second.bill() );
}
} //SYJ
//DiscountSale.h
#ifndef DISCOUNTSALE_H
#define DISCOUNTSALE_H
#include "Sale.h"
namespace SYJ
{
class DiscountSale: public Sale
{
public:
DiscountSale();
DiscountSale(double thePrice, double theDiscount);
double getDiscount() const;
void setDiscount(double newDiscount);
virtual double bill() const; //bill在基类中声明为虚函数,在派生类DiscountSale中自动为虚函数,在声明中可以省略修饰符virtual
private:
double discount;
};
} //SYJ
#endif //DISCOUNT_H
//DiscountSale.cpp
#include "stdafx.h"
#include "DiscountSale.h"
namespace SYJ
{
DiscountSale::DiscountSale() : Sale(), discount(0)
{}
DiscountSale::DiscountSale(double thePrice, double theDiscount)
: Sale(thePrice), discount(theDiscount)
{}
double DiscountSale::getDiscount() const
{
return discount;
}
void DiscountSale::setDiscount(double newDiscount)
{
discount = newDiscount;
}
double DiscountSale::bill() const //函数定义部分不需重复限定词virtual
{
double fraction = discount / 100;
return (1 - fraction) * getPrice();
}
} //SYJ
虚函数,若在某个派生类中给出了新定义,则对于该派生类的任何对象,它总是使用自己给出的虚函数定义。
posted on
浙公网安备 33010602011771号