#include <iostream>
using namespace std;
#include <stdlib.h> //使用srand()函数引入类库
#include <time.h>
class Bakery
{
public:
const double fixedCost; //注意常量的初始化
Bakery();
Bakery(double breadPrice, int breadCount=100); //默认参数放在最后面
Bakery(const Bakery& b); //注意拷贝构造函数的形式
~Bakery();
int GetID(){ //写在类的声明中,隐藏内联函数
return bakeryID;
}
int GetSellBreadCount(){
return sellBreadCount;
}
inline double GetAllProfit(); //显示内联函数
int MakingBread(int n);
double SellBread(int n);
protected:
static int bakeryCount; //注意静态成员变量的初始化
//静态成员必须初始化才可以调用。因为不占用类对象空间,如果不初始化,不会给静态成员分配内存空间,调用时会
int breadCount;
double breadPrice;
int bakeryID;
int sellBreadCount;
double allProfit;
};
// 内联函数只能在头文件中定义,因为编译时需要把内联函数嵌入到程序中。不是调用,所以不能放到.cpp文件中
inline double Bakery::GetAllProfit()
{
return allProfit;
}
int Bakery::bakeryCount = 0; //静态变量初始化最好放在.cpp文件中。放到.h文件中多次引用头文件会冲突
Bakery::Bakery():fixedCost(1.5) //注意常量的初始化
{
//构造函数初始化
breadCount =100;
breadPrice =5;
bakeryID = ++bakeryCount;
sellBreadCount =0;
allProfit =0;
}
Bakery::Bakery(double breadPrice, int breadCount):fixedCost(1.5) //1.默认参数在函数定义中不重复赋值。
{
//注意使用this和没有使用this的区别
this->breadCount =breadCount;
this->breadPrice =breadPrice;
if( this->breadPrice <2 ){ //面包价格不能少于2元
this->breadPrice =2;
}
this->bakeryID = ++bakeryCount;
this->sellBreadCount =0;
this->allProfit =0;
}
Bakery::Bakery(const Bakery& b ):fixedCost(1.5) //常量在每一个构造函数中都要初始化
{
breadCount = b.breadCount;
breadPrice = b.breadPrice;
bakeryID = ++bakeryCount;
sellBreadCount =0;
allProfit =0;
}
Bakery::~Bakery()
{
cout<<"面包店"<<bakeryID<<"关闭!"<<endl;
}
int Bakery::MakingBread(int n)
{
breadCount +=n;
return breadCount;
}
double Bakery::SellBread(int n)
{
if( breadCount<n ){
n = breadCount;
}
double profit = (breadPrice - fixedCost)*n;
allProfit = allProfit + profit;
breadCount =breadCount - n;
sellBreadCount = sellBreadCount + n;
return profit;
}
int main(int argc, char** argv) {
Bakery a;
Bakery b(4,120);
Bakery c(b);
srand(time(NULL)); // time(NULL) 获取当前时间。 以当前时间为随机生成器的种子
for(int i=-0; i<10; i++)
{
a.SellBread( 10 + rand() % 21 ); //随机生成一个10-30的数
a.MakingBread( 10 + rand() % 21 );
b.SellBread( 10 + rand() % 21 );
b.MakingBread( 10 + rand() % 21 );
c.SellBread( 10 + rand() % 21 );
c.MakingBread( 10 + rand() % 21 );
}
cout<<"面包店"<<a.GetID()<<"卖出"<<a.GetSellBreadCount()<<"个面包,获利"<<a.GetAllProfit() <<"元!"<<endl;
cout<<"面包店"<<b.GetID()<<"卖出"<<b.GetSellBreadCount()<<"个面包,获利"<<b.GetAllProfit() <<"元!"<<endl;
cout<<"面包店"<<c.GetID()<<"卖出"<<c.GetSellBreadCount()<<"个面包,获利"<<c.GetAllProfit() <<"元!"<<endl;
//注意 析构函数调用顺序
return 0;
}