|
//头文件
#ifndef STOCK_H_H_
#define STOCK_H_H_
#include<iostream>
using std::ostream;
using std::istream;
class Stock
{
private:
char * str;
int shares;
int len;
double share_val;
double total_val;
void set_tot(){total_val=shares * share_val;}
public:
Stock();
Stock(const char * co,int n=0,double pr=0.0);
~Stock();
void buy(int num,double price);
void sell(int num,double price);
void update(double price);
Stock & operator=(const Stock & s);
Stock & operator=(const char * s);
const Stock & topval(const Stock & s)const;
friend ostream & operator<<(ostream & os,const Stock t);
};
#endif
//源文件
#include<iostream>
#include<cstring>
#include"stock.h"
//using std::ostream;
//using std::istream;
Stock::Stock()
{
len=4;
str=new char[1];
str[0]='\0';
shares=0;
share_val=0.0;
total_val=0.0;
}
Stock::Stock(const char * co,int n,double pr)
{
len=strlen(co);
str=new char[len+1];
strcpy(str,co);
shares=n;
share_val=pr;
set_tot();
}
Stock & Stock::operator=(const Stock & s)
{
if(this==&s)
return *this;
if(str!=0)
delete [] str;
else if(s.len>0)
{
len=s.len;
str=new char[len+1];}
else
{std::cerr<<"len < 0 ";
return *this;
}
if(str==0)
{
std::cerr<<"memor error!\n";
return *this;
}
strcpy(str,s.str);
shares=s.shares;
share_val=s.share_val;
set_tot();
return *this;
}
Stock & Stock::operator=(const char * s)
{
if(str!=0)
delete [] str;
len=strlen(s);
if(len>0)
str=new char[len+1];
else
return *this;
if(str==0)
return *this;
strcpy(str,s);
return *this;
}
Stock::~Stock()
{
delete [] str;
}
void Stock::buy(int num,double price)
{
if(num<0)
{
std::cerr<<"Number of shares purchased can't be negative. "
<<"Transaction is aborted.\n";
}
else
{
shares=shares+num;
share_val=price;
set_tot();
}
}
void Stock::sell(int num,double price)
{
using std::cerr;
if(num<0)
{
cerr<<"Number of shares purchased can't be negative. "
<<"Transaction is aborted.\n";
}
else if(num>shares)
{
cerr<<"You can't sell more than you have! "
<<"Transaction is aborted.\n";
}
else
{
sha |
|