stock cpp

stock.h

#pragma once
#ifndef STOCK_H_
#define STOKC_H_
#include 

class Stock {
private:
	std::string company;
	long 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();
};
#endif

stock.cpp

#include 
#include "stock.h"

Stock::Stock()
{
	std::cout << "Default constructor called\n";
	company = "no name";
	shares = 0;
	share_val = 0.0;
	total_val = 0.0;
}

Stock::Stock(const std::string &co, long n, double pr)
{
	std::cout << "Constructor using " << co << " called\n";
	company = co;

	if (n > 0)
	{
		std::cout << "Number of shares cat'be negative. "
			<< company << " shares set to 0.\n";
		shares = 0;
	}
	else
	{
		shares = n;
	}
	share_val = pr;
	set_tot();
}
void Stock::buy(long num, double price)
{
	if (num < 0)
	{
		std::cout << "Number of shares purchased cat't be negative. "
			<< "Transtaction si 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 cat'be negative. "
			<< "Transaction si aborted.\n";
	}
	else {
		shares -= num;
		share_val = price;
		set_tot();
	}
}

void Stock::update(double price) {
	share_val = price;
	set_tot();
}
void Stock::show() {
	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 << " Share price: $" << share_val<<std::endl;
	cout.precision(2); //设置精确度为2,并返回上一次的设置。
	cout.setf(orig, ios_base::floatfield);
	cout.precision(prec);
}

Stock::~Stock() {
	std::cout << "Bye";
}

useStock.cpp

#include
#include "stock.h"

int main(int argc, char const *argv[])
{
	using std::cout;
	cout << "Using constructors to create new objects\n";
	Stock stock1{ "NanoSmart",12,20.0 };
	stock1.show();
	Stock stock2 = Stock{ "Boff objects",2,2.0 };
	stock2.show();

	cout << "Assigning sokc1 to stock2:\n";
	stock2 = stock1;
	cout << "Listring stock1 and stock2:\n";
	stock1.show();
	stock2.show();

	cout << "Using a construcator to rest an object\n";
	stock1 = Stock{ "Nifty Foods",10,50.0 };
	cout << "Revised stock1:\n";
	stock1.show();
	cout << "Done\n";
	return 0;
}

你可能感兴趣的:(cpp)