stock类
//
// Created by lenovo on 2018/3/18.
//
#ifndef STOCK_STOCK10_H
#define STOCK_STOCK10_H
#include <string>
class stock{
private:
std::string company;
int shares;
double share_val;
double total_val;
void set_tot(){total_val=shares*share_val;}
public:
stock();
stock(const std::string &co,long n=0,double pr=0.0);
~stock();
void buy(long num,double price);
void sell(long num,double price);
void update(double price);
void show()const;
const stock &topval(const stock &s)const;
};
#endif //STOCK_STOCK10_H
//
// Created by lenovo on 2018/3/18.
//
#include <iostream>
#include "stock10.h"
stock::stock() {
company="no name";
shares=0;
share_val=0.0;
total_val=0.0;
}
stock::stock(const std::string &co, long n, double pr) {
company=co;
if(n<0){
std::cout<<"Number of shares can't be negative;"
<<company<<" shares set to 0\n";
shares=0;
}
else
shares=n;
share_val=pr;
set_tot();
}
stock::~stock() {
std::cout<<"Bye!";
}
void stock::buy(long num, double price) {
if(num<0){
std::cout<<"Number of shares purchased can't be negative."
<<"Transaction is aborted.\n";
}
else{
shares+=num;
share_val=price;
set_tot();
}
}
void stock::sell(long num, double price) {
using std::cout;
if(num<0){
cout<<"Number of shares sold can't be negative."
<<"Transaction is aborted.\n";
}
else if(num>shares){
cout<<"you can't sell more than you have!"
<<"Transaction is aborted.\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::ios_base;
ios_base::fmtflags orig=cout.setf(ios_base::fixed,ios_base::floatfield);
std::streamsize prec=cout.precision(3);
cout<<"Company: "<<company
<<" shares: "<<shares<<"\n";
cout<<"shares price: $"<<share_val;
cout.precision(2);
cout<<" Total worth is $"<<total_val<<"\n";
cout.setf(orig,ios_base::floatfield);
cout.precision(prec);
}
const stock&stock::topval(const stock &s) const {
if(s.total_val>total_val)
return s;
else
return *this;
}
#include <iostream>
#include "stock10.h"
const int size=4;
int main()
{
using namespace std;
stock stocks[size]={
stock("Nanosmart",12,20.0),
stock("Boffo objects",200,2.0),
stock("Monolithic obelisks",130,3.25),
stock("Fleep Enterprise",60,6.5)
};
cout<<"stock holding:\n";
int st;
for (int st = 0; st <size ; st++) {
stocks[st].show();
}
const stock*top=&stocks[0];
for (int st = 0; st <size ; st++) {
top=&top->topval(stocks[st]);
}
cout<<"The most valuable holding :\n";
top->show();
return 0;
}