- 论坛徽章:
- 0
|
回复 2# bruceteen
#include<iostream>
#include<cstring>
class Stock
{
private:
char company[30];
int shares;
double share_val;
double total_val;
void set_tot();
//{total_val = share_val * shares;};
public:
Stock();
Stock(char*co,int n,double pr);
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() const;
const Stock& topval(const Stock & s) const;
};
#include<iostream>
#include"stocks.h"
Stock::Stock()
{
strcpy(company,"no name");
shares = 0;
share_val = 0.0;
total_val = 0.0;
}
Stock::Stock(char *co,int n,double pr)
{
strncpy(company,co,29);
company[29] = '\0';
if(n<0)
{
std::cout << "Numbers of shares can't be negative."
<< company << " shares set to 0.\n";
shares = 0;
}
else
{
shares = n;
share_val = pr;
set_tot();
}
}
void Stock::set_tot()
{total_val = shares * share_val;}
void Stock::acquire(const char* co,int n,double pr)
{
strncpy(company,co,29);
company[29] = '\0';
if(n<0)
{
std::cout << "Numbers of shares can't be negative."
<< company << " shares set to 0.\n";
shares = 0;
}
else
{
shares = n;
share_val = pr;
set_tot();
}
}
void Stock::buy(int num,double price)
{
if(num < 0)
{
std::cerr << "Number of shares purchaesd can't be negative. "
"Transaction is aborted.\n";
}
else
{
shares += num;
share_val = price;
set_tot();
}
}
void Stock::sell(int num,double price)
{
using std::cerr;
if(num > shares)
{
cerr << "You can't sell more than you have ! "
<< "Transcation is aborted.\n";
} else if(num < 0)
{
cerr << "Number of shares sold can't be negative."
<< "Transaction is absorted.\n";
}
else
{
shares -= num;
share_val = price;
set_tot();
}
}
void Stock::update(double price)
{
share_val = price;
set_tot();
}
void Stock::show()const
{
using std::cout;
using std::endl;
cout << "Company: " << company << endl;
cout << "Shares: " << shares << endl;
cout << "Share price: $" << share_val << endl;
cout << "Total worth: $" << total_val << endl;
}
const Stock& Stock::topval(const Stock& s)const
{
if(s.total_val>total_val)
return s;
else return *this;
}
#include<iostream>
#include"stocks.h"
const int STKS = 4;
int main()
{
using std::cout ;
using std::ios;
Stock stocks[STKS] =
{
Stock("NanoSmart",12,20.0),
Stock("Boffo Objects",200,2.0),
Stock("Monolithic",130,3.25),
Stock("Fleep Enterprises",60,6.5)
};
cout.precision(2);
// cout.setf(ios::fixed|ios::floatfield);
// cout.setf(ios::showpoint);
cout << "Stock hodings:\n";
int st;
for(st=0;st<STKS;st++)
stocks[st].show();
Stock top = stocks[0];
for(st=1;st<STKS;st++)
top = top.topval(stocks[st]);
cout << "\nMost valuable holding:\n";
top.show();
return 0;
}
|
|