#include <iostream>
#include <cstring>
// 声明一个股票类
class Stock
{
private:
char company[30];
int shares; // 股票数目
double share_val; // 股票价格
double total_val;
void set_total() { total_val = shares * share_val; }
public:
void acqurie(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();
};
// 类方法实现
void Stock::acqurie(const char * co, int n, double pr)
{
strncpy_s(company, co, 29);
company[29] = '\0';
if (n < 0)
{
std::cerr << "持有的股票数目不能为负数!"
<< company << "股票数设为0.\n";
shares = 0;
}
else
shares = n;
share_val = pr;
set_total();
}
void Stock::buy(int num, double price)
{
if (num < 0)
{
std::cerr << "购买的股票数目不能为负数!";
}
else
{
shares += num;
share_val = price;
set_total();
}
}
void Stock::sell(int num, double price)
{
using std::cerr;
if (num < 0)
{
cerr << "不能卖出小于0的股票数目!\n";
}
else if (num > shares)
{
cerr << "您卖出的股票数名,超出您持有的数目!\n";
}
else
{
shares -= num;
share_val = price;
set_total();
}
}
void Stock::update(double price)
{
share_val = price;
set_total();
}
void Stock::show()
{
using std::cout;
using std::endl;
cout << "公司: " << company
<< " 股票数目:" << shares << endl
<< " 股票价格: ¥" << share_val
<< " 总价格: ¥" << total_val << endl;
}
int main()
{
using namespace std;
using std::ios_base;
Stock stock1;
stock1.acqurie("YantaiUniversity", 20, 12.50);
cout.setf(ios_base::fixed);
cout.precision(2);
cout.setf(ios_base::showpoint);
stock1.show();
stock1.buy(15, 18.5);
stock1.show();
stock1.sell(400, 20.00);
stock1.show();
return 0;
}
编译环境是VS 2013 update2,在acqurie()函数中的strncpy_s(), 可以用标准库中的strncpy.