1: //:c08:Quoter.cpp
2: //random quote selection
3: /*
4: *C++编程思想第八章,关于const成员函数的例子
5: *这个例子说明,const对象只能调用cosnt成员函数,例子利用随机数生成器构造了
6: *一个选举器,每次都从若干句话中选出与上次不同的一句话,打印输出。
7: *时间:2011-7-17 10:34
8: *作者:张超
9: *Email:uestczhangchao@gmail.com
10: */
11:
12: #include "X:\编程练习\C-C++\global.h"
13:
14: #if Quoter_cpp==stdon
15: #include <iostream>
16: #include <cstdlib>
17: #include <ctime>
18: using namespace std;
19:
20: class Quoter
21: {
22: int lastquote;
23: public:
24: Quoter();
25: int lastQuote() const;
26: const char* quote();
27: };
28:
29: Quoter::Quoter()
30: {
31: lastquote=-1;
32: srand(time(0));
33: }
34:
35: int Quoter::lastQuote() const
36: {
37: return lastquote;
38: }
39:
40: const char* Quoter::quote()
41: {
42: static const char* quotes[]=
43: {
44: "Are we having fucn yet?",
45: "Doctors always know best!",
46: "Is it ... Atomic",
47: "Fear is obscene",
48: "There is no significant evidence",
49: "to support the idea",
50: "that life is serious",
51: "Things that make us happy, make us wise",
52: "This line is add by JustinZhang",
53: };
54: //对二维指针进行sizeof运算的结果为:(二维指针包含的一位指针的个数)×(一维指针的大小)
55: const int qsize = sizeof quotes/sizeof *quotes;
56: cout << "qsize=" << qsize <<" sizeof quotes="<<sizeof quotes <<" sizeof *quotes="<<sizeof *quotes << endl;
57: int qnum = rand() % qsize;
58: //从quotes中选择一句与上一句不同的话出来。
59: while (lastquote >=0 && qnum==lastquote)
60: {
61: qnum = rand()%qsize;
62: }
63: return quotes[lastquote = qnum];
64: }
65: int main()
66: {
67: Quoter q;
68: const Quoter cq;
69: cq.lastQuote();
70: int a = 0;
71: int c = a&&10/a;
72: cout << c << endl;
73: //cq.quote();
74: for(int i=0; i<20; i++)
75: {
76: cout << q.quote() << endl;
77:
78: }
79: system("pause");
80: }
81:
82: #endif