#include<iostream>
#include<cstring>
using namespace std;
class stock
{
private:
char copany[30];
int shares;
double share_val;
double total_val;
void set_tot (){total_val = shares * share_val;}
public:
void acquire (const char * co,int n,double pr);
void buy (int num ,double price);
void sell (int num,double price);
void update (double price);
void show();
};
void stock::acquire(const char * co,int n,double pr)
{
strncpy(company,co,29);
company [29] = '\0';
if(n<0)
{
cerr << "numble of shares can't be negative:"
<<"shares set to 0.\n";
shares = 0;
}
else shares =n;
shares_val =pr;
set_tot();
}
void stock:: buy (int num,double price)
{
if (num<0)
{
cerr<<"number of shares purchaseed can't be negative."
<<"Transaction is aborted.\n";
}
else{
shares += num;
share_val = price;
set_tot ();
}
}
void stock:: sell (int num,double price)
{
if (num<0)
{
cerr<< "number of shares sold can't be negative."
<<"Transaction is aborted.\n";
}
else if (num > shares)
{
cerr<<"You can't sell more than you have !"
<<"Thansaction is aborted.\n";
}
else
{
shares -=num;
share_val = price;
set_tot();
}
}
void stock:: update (double price)
{
share_val = price;
set_tot();
}
void stock::show()
{
cout<<"company:"<<company
<<"shares:"<<shares<<'\n'
<<"share price: $"<<share_val
<<"total worth:$"<<total_val<<'\n';
}
int main()
{
stock stock1;
stock1.acquire("nanosmart",20,12.50);
cout.self(ios_base::fixed);
cout.precision(2);
cout.self(ios_base::showpoint);
stock1.show();
stock1.buy(15,18.25);
stock1.show();
stock.sell(400,20.00);
stock1.show();
return 0;
}
[此贴子已经被作者于2006-11-22 12:29:37编辑过]