[C++ Primer Plus] 第10章、对象和类——(一)程序清单

程序清单10.1+10.2+10.3

头文件stock00.h
 1 //stock00.h
 2 #ifndef STOCK00_H_    //如果没有定义STOCK00_H_
 3 #define STOCK00_H_    //那么就定义STOCK00_H_
 4 
 5 #include<string>
 6 using namespace std;
 7 
 8 class Stock    //类声明
 9 {
10 private:
11     string company;
12     long shares;
13     double share_val;
14     double total_val;
15     void set_tot();
16 public:
17     void acquire(const string &co, long n, double pr);
18     void buy(long num, double price);
19     void sell(long num, double price);
20     void update(double price);
21     void show();
22 };
23 
24 inline void Stock::set_tot()   //内联函数 或者按书上那种写法,两种一样
25 {
26     total_val = shares*share_val;
27 }
28 
29 #endif // !STOCK00_H_  结束预定义

 stock00.cpp

 1 #include<iostream>
 2 #include"stock00.h"
 3 using namespace std;
 4 
 5 void Stock::acquire(const string &co, long n, double pr)
 6 {
 7     company = co;
 8     if (n < 0)
 9     {
10         cout << "shares can't be negative." << company << " shares set to 0.\n";
11         shares = 0;
12     }
13     else
14         shares = n;
15     share_val = pr;
16     set_tot();
17 }
18 void Stock::buy(long num, double price)
19 {
20     if (num < 0)
21         cout << "shares purchased can't be negative.\n";    
22     else
23     {
24         shares += num;
25         share_val = price;
26         set_tot();
27     }
28 }
29 void Stock::sell(long num, double price)
30 {
31     if (num < 0)
32         cout << "shares sold can't be negative.\n";
33     else if (num > shares)
34         cout << "you can't sell more than you have.\n";
35     else
36     {
37         shares -= num;
38         share_val = price;
39         set_tot();
40     }
41 }
42 void Stock::update(double price)
43 {
44     share_val = price;
45     set_tot();
46 }
47 void Stock::show()
48 {
49     cout << "Company: " << company
50         << " Shares: " << shares << "\n"
51         << " Share Price: $ " << share_val
52         << " Tptal Worth: & " << total_val << "\n";
53 }

usestock0.cpp

 1 #include<iostream>
 2 #include"stock00.h"
 3 using namespace std;
 4 
 5 int main() 
 6 {
 7     Stock cat;
 8     cat.acquire("NanoSmart", 20, 12.50);
 9     cat.show();
10     cat.buy(15, 18.125);
11     cat.show();
12     cat.sell(400, 20.0);
13     cat.show();
14     cat.buy(300000, 40.125);
15     cat.show();
16     cat.sell(300000, 0.125);
17     cat.show();
18 
19     system("pause");
20     return 0;
21 }

[C++ Primer Plus] 第10章、对象和类——(一)程序清单

 

 修改stock.cpp文件中的show方法,使其数字格式统一

 1 void Stock::show()
 2 {
 3     //将原始格式存入orig,设置cout对象的一个标记
 4     //ios_base::fixed命令cout使用定点表示法,ios_base::floatfield设置输出时按浮点格式,小数点后有6位数
 5     ios_base::fmtflags orig = cout.setf(ios_base::fixed, ios_base::floatfield);
 6     //streamsize可以设置输入流的位数
 7     //cout使用定点表示法时,显示三位小数
 8     //保存当前流的位数到prec中
 9     std::streamsize prec = cout.precision(3);
10 
11     cout << "Company: " << company
12         << ", Shares:" << shares
13         << "\nShare Price: $" << share_val;
14     cout.precision(2);
15     cout << ", Total Worth: $" << total_val << '\n';
16     
17     //返回调用show()之前的格式
18     cout.setf(orig, ios_base::floatfield);
19     cout.precision(prec);
20 }

[C++ Primer Plus] 第10章、对象和类——(一)程序清单

构造函数和析构函数

程序清单10.4+10.5+10.6

头文件stock10.h

 1 //stock10.h
 2 #ifndef STOCK00_H_    //如果没有定义STOCK00_H_
 3 #define STOCK00_H_    //那么就定义STOCK00_H_
 4 
 5 #include<string>
 6 using namespace std;
 7 
 8 class Stock    //类声明
 9 {
10 private:
11     string company;
12     long shares;
13     double share_val;
14     double total_val;
15     void set_tot();
16 public:
17     Stock();   //默认构造函数
18     Stock(const string &co, long n = 0, double pr = 0.0); //构造函数,和前面例子中的acquire()相同,区别在于,程序声明对象时,将自动调用构造函数
19     ~Stock();  //析构函数
20     void buy(long num, double price);
21     void sell(long num, double price);
22     void update(double price);
23     void show();
24 };
25 
26 inline void Stock::set_tot()   //内联函数 或者按书上那种写法,两种一样
27 {
28     total_val = shares*share_val;
29 }
30 
31 #endif // !STOCK00_H_  结束预定义

函数定义stock10.cpp

 1 #include<iostream>
 2 #include"stock10.h"
 3 using namespace std;
 4 
 5 //默认构造函数
 6 Stock::Stock()
 7 {
 8     cout << "Default constructor called\n";
 9     company = "no name";
10     shares = 0;
11     share_val = 0.0;
12     total_val = 0.0;
13 }
14 
15 //构造函数
16 Stock::Stock(const string &co, long n, double pr)
17 {
18     cout << "Constructor using " << co << " called\n";
19     company = co;
20     if (n < 0)
21     {
22         cout << "shares can't be negative." << company << " shares set to 0.\n";
23         shares = 0;
24     }
25     else
26         shares = n;
27     share_val = pr;
28     set_tot();
29 }
30 
31 //析构函数
32 Stock::~Stock()
33 {
34     cout << "Bye, " << company << "!\n";
35 }
36 
37 //其他方法
38 void Stock::buy(long num, double price)
39 {
40     if (num < 0)
41         cout << "shares purchased can't be negative.\n";    
42     else
43     {
44         shares += num;
45         share_val = price;
46         set_tot();
47     }
48 }
49 
50 void Stock::sell(long num, double price)
51 {
52     if (num < 0)
53         cout << "shares sold can't be negative.\n";
54     else if (num > shares)
55         cout << "you can't sell more than you have.\n";
56     else
57     {
58         shares -= num;
59         share_val = price;
60         set_tot();
61     }
62 }
63 void Stock::update(double price)
64 {
65     share_val = price;
66     set_tot();
67 }
68 void Stock::show()
69 {
70     //将原始格式存入orig,设置cout对象的一个标记
71     //ios_base::fixed命令cout使用定点表示法,ios_base::floatfield设置输出时按浮点格式,小数点后有6位数
72     ios_base::fmtflags orig = cout.setf(ios_base::fixed, ios_base::floatfield);
73     //streamsize可以设置输入流的位数
74     //cout使用定点表示法时,显示三位小数
75     //保存当前流的位数到prec中
76     std::streamsize prec = cout.precision(3);
77 
78     cout << "Company: " << company
79         << ", Shares:" << shares
80         << "\nShare Price: $" << share_val;
81     cout.precision(2);
82     cout << ", Total Worth: $" << total_val << '\n';
83     
84     //返回调用show()之前的格式
85     cout.setf(orig, ios_base::floatfield);
86     cout.precision(prec);
87 }

主函数usestock1.cpp

 1 #include<iostream>
 2 #include"stock10.h"
 3 using namespace std;
 4 
 5 int main() 
 6 {
 7     //大括号的作用:stock1和stock2等自动变量将在程序退出其定义所属代码块时消失
 8     //如果没有大括号,代码块将为整个main(),因此main()执行完,到达返回语句之后,才会调用析构函数,会看不到最后两条消息。
 9     {
10         cout << "Using constructors to create new objects\n";
11         Stock stock1("NanoSmart", 12, 20.0);    //隐式调用构造函数
12         stock1.show();
13         Stock stock2 = Stock("Boffo Objects", 2, 2.0);    //显式调用构造函数
14         stock2.show();
15 
16         cout << "Assigning stock1 to stock2!!!\n";   //将stock1分配给stock2!!!
17         stock2 = stock1;
18         cout << "Listing stock1 and stock2:\n";
19         stock1.show();
20         stock2.show();
21 
22         cout << "Using a constructor to reset an object!!!\n";  //用构造函数重置对象
23         stock1 = Stock("Nifty Foods", 10, 50.0);
24         cout << "Revised stock1:\n";  //修订stock1
25         stock1.show();
26         cout << "Done\n";
27     }
28     system("pause");
29     return 0;
30 }

[C++ Primer Plus] 第10章、对象和类——(一)程序清单

程序清单10.7+10.8+10.9(this指针+对象数组)

红色标记为相较于上一个例子新增的东西

头文件stock20.h

 1 //stock20.h
 2 #ifndef STOCK00_H_    //如果没有定义STOCK00_H_
 3 #define STOCK00_H_    //那么就定义STOCK00_H_
 4 
 5 #include<string>
 6 using namespace std;
 7 
 8 class Stock    //类声明
 9 {
10 private:
11     string company;
12     long shares;
13     double share_val;
14     double total_val;
15     void set_tot();
16 public:
17     Stock();   //默认构造函数
18     Stock(const string &co, long n = 0, double pr = 0.0); //构造函数,和前面例子中的acquire()相同,区别在于,程序声明对象时,将自动调用构造函数
19     ~Stock();  //析构函数
20     void buy(long num, double price);
21     void sell(long num, double price);
22     void update(double price);
23     //show()要加const,后面top要调用show(),是隐式访问的对象,所以类型要一致
24     void show()const;
25     //新增
26     const Stock & topval(const Stock & s)const;
27 };
28 
29 inline void Stock::set_tot()   //内联函数 或者按书上那种写法,两种一样
30 {
31     total_val = shares*share_val;
32 }
33 
34 #endif // !STOCK00_H_  结束预定义

函数定义stock20.cpp

 1 #include<iostream>
 2 #include"stock20.h"
 3 using namespace std;
 4 
 5 //默认构造函数
 6 Stock::Stock()
 7 {
 8     company = "no name";
 9     shares = 0;
10     share_val = 0.0;
11     total_val = 0.0;
12 }
13 
14 //构造函数
15 Stock::Stock(const string &co, long n, double pr)
16 {
17     //cout << "Constructor using " << co << " called\n";
18     company = co;
19     if (n < 0)
20     {
21         cout << "shares can't be negative." << company << " shares set to 0.\n";
22         shares = 0;
23     }
24     else
25         shares = n;
26     share_val = pr;
27     set_tot();
28 }
29 
30 //析构函数
31 Stock::~Stock()
32 {
33 }
34 
35 //其他方法
36 void Stock::buy(long num, double price)
37 {
38     if (num < 0)
39         cout << "shares purchased can't be negative.\n";    
40     else
41     {
42         shares += num;
43         share_val = price;
44         set_tot();
45     }
46 }
47 
48 void Stock::sell(long num, double price)
49 {
50     if (num < 0)
51         cout << "shares sold can't be negative.\n";
52     else if (num > shares)
53         cout << "you can't sell more than you have.\n";
54     else
55     {
56         shares -= num;
57         share_val = price;
58         set_tot();
59     }
60 }
61 void Stock::update(double price)
62 {
63     share_val = price;
64     set_tot();
65 }
66 void Stock::show()const
67 {
68     //将原始格式存入orig,设置cout对象的一个标记
69     //ios_base::fixed命令cout使用定点表示法,ios_base::floatfield设置输出时按浮点格式,小数点后有6位数
70     ios_base::fmtflags orig = cout.setf(ios_base::fixed, ios_base::floatfield);
71     //streamsize可以设置输入流的位数
72     //cout使用定点表示法时,显示三位小数
73     //保存当前流的位数到prec中
74     std::streamsize prec = cout.precision(3);
75 
76     cout << "Company: " << company
77         << ", Shares:" << shares
78         << "\nShare Price: $" << share_val;
79     cout.precision(2);
80     cout << ", Total Worth: $" << total_val << '\n';
81     
82     //返回调用show()之前的格式
83     cout.setf(orig, ios_base::floatfield);
84     cout.precision(prec);
85 }
86 
87 //新增
88 const Stock & Stock::topval(const Stock & s)const
89 {
90     if (s.total_val > total_val)
91         return s;
92     else
93         return *this;
94 }

主函数usestock2.cpp (都改了,添加了对象数组)

 1 #include<iostream>
 2 #include"stock10.h"
 3 using namespace std;
 4 
 5 const int STKS = 4;
 6 
 7 int main() 
 8 {
 9     //创建一个初始化对象数组
10     Stock stocks[STKS] =
11     {
12         Stock("NS",12,20.0),
13         Stock("B O",200,2.0),
14         Stock("M O",130,3.25),
15         Stock("F E",60,6.5)
16     };
17     cout << "Stock holding: " << endl;
18     int st;
19     for (st = 0; st < STKS; st++)
20     {
21         stocks[st].show();
22     }
23     //让top指针指向第一个元素
24     const Stock *top = &stocks[0];
25     //topval()每次只检查两个对象,所以程序使用for循环来检查整个数组
26     for (st = 1; st < STKS; st++)
27     {
28         top =&top -> topval(stocks[st]);  //->的优先级高于&,所以可以看成top = & (top -> topval(stocks[st]));
29                                           //先用top调用topval(),将返回的对象的地址赋给top
30     }
31     cout << "\nmost valuable holding : \n";
32     top->show();
33 
34     system("pause");
35     return 0;
36 }

[C++ Primer Plus] 第10章、对象和类——(一)程序清单

程序清单10.10+10.11+10.12

头文件stack.h

//stack.h
#ifndef STACK_H_    //如果没有定义SSTACK_H_
#define STACK_H_    //那么就定义STACK_H_
typedef unsigned long Item;

class Stack        //类声明
{
private:
    enum { MAX = 10 };
    Item items[MAX];
    int top;
public:
    Stack();    //默认构造函数
    bool isempty() const;
    bool isfull() const;
    bool push(const Item & item);//压栈
    bool pop(Item & item);//出栈
};

#endif // !STOCK00_H_  结束预定义

 

函数定义stack.cpp

 1 #include "stack.h"
 2 
 3 //构造函数
 4 Stack::Stack()   //创建一个空栈
 5 {
 6     top = 0;
 7 }
 8 
 9 bool Stack::isempty() const 
10 {
11     return top == 0;//top为0返回true,反之为false
12 }
13 bool Stack::isfull() const 
14 {
15     return top == MAX;
16 }
17 bool Stack::push(const Item &item) 
18 {
19     if (top<MAX) 
20     {
21         items[top++] = item;
22         return true;
23     }
24     else
25         return false;
26 }
27 bool Stack::pop(Item &item) 
28 {
29     if (top>0) 
30     {
31         item = items[--top];
32         return true;
33     }
34     else
35         return false;
36 }

主函数stacker.cpp

 1 #include<iostream>
 2 #include<cctype>
 3 #include "stack.h"
 4 using namespace std;
 5 
 6 void main() 
 7 {
 8     Stack st;
 9     char ch;
10     unsigned long po;
11     cout << "Enter A to add a purchase order, P to process a PO, Q to quit.\n";
12     while (cin >> ch&&toupper(ch) != 'Q')
13     {
14         while (cin.get() != '\n')//如果不是换行就继续
15             continue;
16         if (!isalpha(ch))//如果不是字母就继续
17         {
18             cout << '\a';
19             continue;
20         }
21         switch (ch)
22         {
23         case 'A':
24         case 'a':
25             cout << "Enter a PO number to add: ";
26             cin >> po;
27             if (st.isfull())//该方法判断:如果满了(top等于MAX)返回true,没满返回false
28                 cout << "Stack already full\n";
29             else
30                 st.push(po);
31             break;
32         case 'P':
33         case 'p':
34             if (st.isempty())
35                 cout << "Stack already empty\n";
36             else 
37             {
38                 st.pop(po);
39                 cout << "PO #" << po << " popped\n";
40             }
41             break;
42         }
43         cout << "Enter A to add a purchase order, P to process a PO, Q to quit.\n";
44     }
45     system("pause");
46 }

[C++ Primer Plus] 第10章、对象和类——(一)程序清单

 

上一篇:LeetCode 第 901 题:股票价格跨度(单调栈)


下一篇:股价翻番 人生赢家,python爬取基金 筛选股票