会飞的蝌蚪君

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

定义类,类的数据表示、类的成员函数、以及对象的创建、成员的调用

  1 #include "stdafx.h"
  2 #include <iostream>
  3 #include<cstring>
  4 
  5 using namespace std;
  6 
  7 class Stock
  8 {
  9     char company[30];
 10     int shares;
 11     double share_val;
 12     double total_val;
 13     void set_tot() { total_val = shares * share_val; }
 14 
 15 public:
 16 
 17     void acquire(const char* co, int n, double pr);
 18     void buy(int num, double price);
 19     void sell(int num, double price);
 20     void update(double price);
 21     void show();
 22 };
 23 
 24 
 25 
 26 void Stock::acquire(const char* co, int n, double pr)
 27 {
 28     
 29     strncpy_s(company, co, 29);  //strncpy_s复制完后能够自动在字符串后面加‘\0’
 30     //company[29] = '\0';
 31     if (n < 0)
 32     {
 33         cerr << "所拥有的股票数目不能为负值!" << company << "数目置零" << endl;
 34         shares = 0;
 35     }
 36     else
 37     
 38         shares = n;
 39     share_val = pr;
 40     set_tot();
 41     
 42 }
 43 
 44 void Stock::buy(int num, double price)
 45 {
 46     if (num < 0)
 47     {
 48         cerr << "购买的股票数目不能为负值" << "交易关闭" << endl;
 49 
 50     }
 51     else
 52     {
 53         shares += num;
 54         share_val = price;
 55         set_tot();
 56     }
 57     
 58 
 59 }
 60 
 61 
 62 
 63 void Stock::sell(int num, double price)
 64 {
 65     if (num < 0)
 66     {
 67         cerr << "购买的股票数目不能为负值" << "交易关闭" << endl;
 68 
 69     }
 70     else if (num>shares)
 71     {
 72         cerr << "您的数量有限,无法售出" << endl;
 73 
 74     }
 75     else
 76     {
 77         shares -= num;
 78         share_val = price;
 79         set_tot();
 80 
 81     }
 82 }
 83 
 84 
 85 void Stock::update(double price)
 86 {
 87     share_val = price;
 88     set_tot();
 89 }
 90 
 91 
 92 void Stock::show()
 93 {
 94     cout << "company = " << company << endl;
 95     cout << "shares = " << shares << endl;
 96     cout << "share price = $" << share_val << endl;
 97     cout << "total worth = $" << total_val << endl;
 98 
 99 }
100 
101 
102 
103 int main()
104 {
105 
106     Stock stock1;
107     stock1.acquire("NanoSmart", 20, 12.50);
108     cout.setf(ios_base::fixed);
109     cout.precision(2);
110     cout.setf(ios_base::showpoint);
111     stock1.show();
112     stock1.buy(15,18.25);
113     stock1.show();
114     stock1.sell(400, 20.00);
115     stock1.show();
116     system("pause");
117     return 0;
118 
119 }

 

posted on 2018-03-29 18:46  会飞的蝌蚪  阅读(128)  评论(0)    收藏  举报