c++primer plus第六版第十二章第三题

#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);
	//void show()const;
	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();

}
//void stock::show()const;
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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值