#pragma once
#include<iostream>
class stock
{
char*str;
int shares;
double share_val;
double total_val;
void set_tot() { total_val = shares * share_val; };
public:
stock();
stock(const char *p, int a, double b);
stock(const stock&a);
stock &operator=(const stock&a);
void buy(long num, double price);
void sell(long num, double price);
void update(double price);
const stock&topval(const stock&s)const;
friend std::ostream &operator<<(std::ostream&os, const stock&a);
~stock();
};
```cpp
#include "stock.h"
#include<cstring>
#include<iostream>
stock::stock()
{
str = new char[1];
str[0] = '\0';
shares = 0;
share_val = 0;
total_val = 0;
}
stock::stock(const char *p, int a, double b)
{
str = new char[std::strlen(p) + 1];
strcpy_s(str, std::strlen(p) + 1, p);
shares = a;
share_val =b;
set_tot();
}
stock::stock(const stock&a)
{
str = new char[std::strlen(a.str) + 1];
strcpy_s(str, std::strlen(a.str) + 1, a.str);
shares = a.shares;
share_val = a.share_val;
set_tot();
}
stock &stock::operator=(const stock&a)
{
if (this ==&a)
return *this;
delete[]str;
str = new char[std::strlen(a.str) + 1];
strcpy_s(str, std::strlen(a.str) + 1, a.str);
shares = a.shares;
share_val = a.share_val;
set_tot();
return *this;
}
void stock::buy(long num, double price)
{
shares += num;
share_val = price;
set_tot();
}
void stock::sell(long num, double price)
{
if (shares < num)
std::cout << "wrong";
shares -= num;
share_val = price;
set_tot();
}
void stock::update(double price)
{
share_val = price;
set_tot();
}
const stock&stock::topval(const stock&s)const
{
if (s.total_val > total_val)
return s;
else
return *this;
}
std::ostream &operator<<(std::ostream&os, const stock&a)
{
os << "name:" << a.str << "\n"
<< "share:" << a.shares << "\n"
<< "share_val:" << a.share_val << "\n"
<< "total:" << a.total_val << "\n";
return os;
}
stock::~stock()
{
delete[]str;
}
```cpp
#include<iostream>
#include"stock.h"
const int stk = 4;
int main()
{
stock stocks[stk] = {
stock("kangkang",12,20.0),
stock("heelo",201,2.2),
stock("feel",130,3.25),
stock("sygeg",60,6.5),
};
for (int i = 0;i < stk; i++)
{
std::cout << stocks[i];
}
stock a = stock("jjs", 200, 2.0);
stocks[1] = a;
std::cout << stocks[1];
const stock*p = &stocks[0];
for (int i = 0; i < stk; i++)
{
p = &p->topval(stocks[i]);
}
std::cout << *p;
system("pause");
return 0;
}