c++对象重新学习之一——股票交易

#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.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值