《C++游戏编程》基础

来源:互联网 发布:js 调用data-toggle 编辑:程序博客网 时间:2024/05/21 17:30

Beginning C++ Through Came Programming

2017.03.14 - 2017.03.17

简单编程熟悉概念,四天全部看完。

(001) 致谢

赠人玫瑰,手有余香

Finally, I want to thank all of the game programmers who created the games I played while growing up. They inspired me to work in the industry and create games of my own. I hope I can inspire a few readers to do the same.

(002) 目录

Chapter 01: Types, Variables, and Standard I/O: Lost Fortune

Chapter 02: Truth, Branching, and the Game Loop: Guess My Number

Chapter 03: for Loops, Strings, and Arrays: Word Jumble

Chapter 04: The Standard Template Library: Hangman

Chapter 05: Functions: Mad Lib

Chapter 06: References: Tic-Tac-Toe

Chapter 07: Pointers: Tic-Tac-Toe 2.0

Chapter 08: Classes: Critter Caretaker

Chapter 09: Advanced Classes and Dynamic Memory: Game Lobby

Chapter 10: Inheritance and Polymorphism: Blackjack

Appendix

(003) C++语言对于游戏的重要性

If you were to wander the PC game section of your favorite store and grab a title at random, the odds are overwhelming that the game in your hand would be written largely or exclusively in C++.

(004) 本书目标

The goal of this book is to introduce you to the C++ language from a game programming perspective.

By the end of this book, you'll have a solid foundation in the game programming language of the professionals.


Chapter 1: Types, Variables, And Standard I/O: Lost Fortune

(005) 第一个游戏

The Game Over program puts a gaming twist on the classic and displays Game Over! instead.

[html] view plain copy
  1. 1 // Game Over  
  2.  2 // A first C++ program  
  3.  3 #include <iostream>  
  4.  4   
  5.  5 int main()  
  6.  6 {  
  7.  7     std::cout << "Game Over!" << std::endl;  
  8.  8     return 0;  
  9.  9 }  
wang@wang:~/workspace/beginc++game$ ./game_over 
Game Over!

(006) ostream

cout is an object, defined in the file iostream, that's used to send data to the standard output stream.

(007) 使用std directive

[html] view plain copy
  1.  1 // Game Over 2.0  
  2.  2 // Demonstrates a using directive  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 using namespace std;  
  6.  6   
  7.  7 int main()  
  8.  8 {  
  9.  9     cout << "Game Over!" << endl;  
  10. 10     return 0;  
  11. 11 }  
wang@wang:~/workspace/beginc++game$ ./game_over2 
Game Over!
(008) 使用using declaration

[html] view plain copy
  1.  1 // Game Over 3.0  
  2.  2 // Demonstrates using declarations  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 using std::cout;  
  6.  6 using std::endl;  
  7.  7   
  8.  8 int main()  
  9.  9 {  
  10. 10     cout << "Game Over!" << endl;  
  11. 11     return 0;  
  12. 12 }  
wang@wang:~/workspace/beginc++game$ ./game_over3
Game Over!

(009) 加减乘除

[html] view plain copy
  1.  1 // Expensive Calculator  
  2.  2 // Demonstrates built-in arithmetic operators  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 using namespace std;  
  6.  6   
  7.  7 int main()  
  8.  8 {  
  9.  9     cout << "7 + 3 = " << 7 + 3 << endl;  
  10. 10     cout << "7 - 3 = " << 7 - 3 << endl;  
  11. 11     cout << "7 * 3 = " << 7 * 3 << endl;  
  12. 12   
  13. 13     cout << "7 / 3 = " << 7 / 3 << endl;  
  14. 14     cout << "7.0 / 3.0 = " << 7.0 / 3.0 << endl;  
  15. 15   
  16. 16     cout << "7 % 3 = " << 7 % 3 << endl;  
  17. 17   
  18. 18     cout << "7 + 3 * 5 = " << 7 + 3 * 5 << endl;  
  19. 19     cout << "(7 + 3) * 5 = " << (7 + 3) * 5 << endl;  
  20. 20   
  21. 21     return 0;  
  22. 22 }  
wang@wang:~/workspace/beginc++game$ ./expensive_calculator 
7 + 3 = 10
7 - 3 = 4
7 * 3 = 21
7 / 3 = 2
7.0 / 3.0 = 2.33333
7 % 3 = 1
7 + 3 * 5 = 22
(7 + 3) * 5 = 50

(010) 变量

A variable represents a particular piece of your computer's memory that has been set aside for you to use to store, retrieve, and manipulate data.

(011) 状态值举例

[html] view plain copy
  1.  1 // Game Stats  
  2.  2 // Demonstrates declaring and initializing variables  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 using namespace std;  
  6.  6   
  7.  7 int main()  
  8.  8 {  
  9.  9     int score;  
  10. 10     double distance;  
  11. 11     char playAgain;  
  12. 12     bool shieldsUp;  
  13. 13   
  14. 14     short lives, aliensKilled;  
  15. 15   
  16. 16     score = 0;  
  17. 17     distance = 1200.76;  
  18. 18     playAgain = 'y';  
  19. 19     shieldsUp = true;  
  20. 20     lives = 3;  
  21. 21     aliensKilled = 10;  
  22. 22     double engineTemp = 6572.89;  
  23. 23   
  24. 24     cout << "score: " << score << endl;  
  25. 25     cout << "distance: " << distance << endl;  
  26. 26     cout << "playAgain: " << playAgain << endl;  
  27. 27     // skipping shieldsUp since you don't generally print Boolean values  
  28. 28     cout << "lives: " << lives << endl;  
  29. 29     cout << "aliensKilled: " << aliensKilled << endl;  
  30. 30     cout << "engineTemp: " << engineTemp << endl;  
  31. 31   
  32. 32     int fuel;  
  33. 33     cout << "How much fuel? ";  
  34. 34     cin >> fuel;  
  35. 35     cout << "fuel: " << fuel << endl;  
  36. 36   
  37. 37     typedef unsigned short int ushort;  
  38. 38     ushort bonus = 10;  
  39. 39     cout << "bonus: " << bonus << endl;  
  40. 40   
  41. 41     return 0;  
  42. 42 }  

wang@wang:~/workspace/beginc++game$ ./game_stats 
score: 0
distance: 1200.76
playAgain: y
lives: 3
aliensKilled: 10
engineTemp: 6572.89
How much fuel? 12
fuel: 12
bonus: 10

(012) modifier

signed and unsigned are modifiers  that work only with integer types.

(013) identifier命名规则

1. Choose descriptive names

2. Be consistent

3. Follow the traditions of the language

4. Keep the length in check

(014) typedef定义

To define new names for existing types, use typedef followed by the current type, followed by the new name.

(015) 变量运算举例

[cpp] view plain copy
  1.  1 // Game Stats 2.0  
  2.  2 // Demonstrates arithmetic operations with variables  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 using namespace std;  
  6.  6   
  7.  7 int main()  
  8.  8 {  
  9.  9     unsigned int score = 5000;  
  10. 10     cout << "score: " << score << endl;  
  11. 11   
  12. 12     // altering the value of a variable  
  13. 13     score = score + 100;  
  14. 14     cout << "score: " << score << endl;  
  15. 15   
  16. 16     // combined assignment operator  
  17. 17     score += 100;  
  18. 18     cout << "score: " << score << endl;  
  19. 19   
  20. 20     // increment operators  
  21. 21     int lives = 3;  
  22. 22     ++lives;  
  23. 23     cout << "lives: " << lives << endl;  
  24. 24   
  25. 25     lives = 3;  
  26. 26     lives++;  
  27. 27     cout << "lives: " << lives << endl;  
  28. 28   
  29. 29     lives = 3;  
  30. 30     int bonus = ++lives * 10;  
  31. 31     cout << "lives, bonus = " << lives << ", " << bonus << endl;  
  32. 32   
  33. 33     lives = 3;  
  34. 34     bonus = lives++ * 10;  
  35. 35     cout << "lives, bonus = " << lives << ", " << bonus << endl;  
  36. 36   
  37. 37     // integer wrap around  
  38. 38     score = 4294967295;  
  39. 39     cout << "socre: " << score << endl;  
  40. 40     ++score;  
  41. 41     cout << "score: " << score << endl;  
  42. 42   
  43. 43     return 0;  
  44. 44 }  
wang@wang:~/test$ ./game_stat2 
score: 5000
score: 5100
score: 5200
lives: 4
lives: 4
lives, bonus = 4, 40
lives, bonus = 4, 30
socre: 4294967295
score: 0
(016) wrap around溢出

Make sure to pick an integer type that has a large enough range for its intended use.

(017) 常量

First, they make programs clearer.

Second, constants make changes easy.

(018) 枚举类型举例

An enumeration is a set of unsigned int constants, called enumerators. 

[cpp] view plain copy
  1.  1 // Game Stats 3.0  
  2.  2 // Demonstrates constants  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 using namespace std;  
  6.  6   
  7.  7 int main()  
  8.  8 {  
  9.  9     const int ALIEN_POINTS = 150;  
  10. 10     int aliensKilled = 10;  
  11. 11     int score = aliensKilled * ALIEN_POINTS;  
  12. 12     cout << "score: " << score << endl;  
  13. 13     enum difficulty {NOVICE, EASY, NORMAL, HARD, UNBEATABLE};  
  14. 14     difficulty myDifficulty = EASY;  
  15. 15     enum shipCost {FIGHTER_COST = 25, BOMBER_COST, CRUISER_COST = 50};  
  16. 16     shipCost myShipCost = BOMBER_COST;  
  17. 17     cout << "To upgrade my ship to a Cruiser will cost "  
  18. 18         << (CRUISER_COST - myShipCost) << " Resource Points.\n";  
  19. 19     return 0;  
  20. 20 }  
wang@wang:~/test$ ./game_stats3 
score: 1500
To upgrade my ship to a Cruiser will cost 24 Resource Points.
(019) 综合举例

有趣的文字游戏

[cpp] view plain copy
  1.  1 // Lost Fortune  
  2.  2 // A personalized adventure  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 #include <string>  
  6.  6   
  7.  7 using namespace std;  
  8.  8 int main()  
  9.  9 {  
  10. 10     const int GOLD_PIECES = 900;  
  11. 11     int adventurers, killed, survivors;  
  12. 12     string leader;  
  13. 13   
  14. 14     // get the information  
  15. 15     cout << "Welcome to Lost Fortune\n";  
  16. 16     cout << "Please enter the following for your personalized adventure\n";  
  17. 17     cout << "Enter a number: ";  
  18. 18     cin >> adventurers;  
  19. 19     cout << "Enter a number, smaller than the first: ";  
  20. 20     cin >> killed;  
  21. 21     survivors = adventurers - killed;  
  22. 22     cout << "Enter your last name: ";  
  23. 23     cin >> leader;  
  24. 24     // tell the story  
  25. 25     cout << "A brave group of " << adventurers << " set out on a quest ";  
  26. 26     cout << "-- in search of the lost treasure of the Ancient Dwarves. ";  
  27. 27     cout << "The group was led by that legendary rogue, " << leader << ".\n";  
  28. 28     cout << "Along the way, a band of marauding ogres ambushed the party. ";  
  29. 29     cout << "All fought bravely under the command of " << leader;  
  30. 30     cout << ", and the ogres were defeated, but at a cost. ";  
  31. 31     cout << "Of the adventurers, " << killed << " were vanquished, ";  
  32. 32     cout << "leaving just " << survivors << " in the group.\n";  
  33. 33     cout << "The party was about to give up all hope. ";  
  34. 34     cout << "But while laying the deceased to rest, ";  
  35. 35     cout << "they stumbled upon the buried fortune. ";  
  36. 36     cout << "So the adventurers split " << GOLD_PIECES << " gold pieces. ";  
  37. 37     cout << leader << " held on to the extra " << (GOLD_PIECES % survivors);  
  38. 38     cout << " pieces to keep things fair of cource.\n";  
  39. 39     return 0;  
  40. 40 }  
wang@wang:~/test$ g++ lost_fortune.cpp -o lost_fortune
wang@wang:~/test$ ./lost_fortune 
Welcome to Lost Fortune
Please enter the following for your personalized adventure
Enter a number: 19
Enter a number, smaller than the first: 13
Enter your last name: wang
A brave group of 19 set out on a quest -- in search of the lost treasure of the Ancient Dwarves. The group was led by that legendary rogue, wang.
Along the way, a band of marauding ogres ambushed the party. All fought bravely under the command of wang, and the ogres were defeated, but at a cost. Of the adventurers, 13 were vanquished, leaving just 6 in the group.
The party was about to give up all hope. But while laying the deceased to rest, they stumbled upon the buried fortune. So the adventurers split 900 gold pieces. wang held on to the extra 0 pieces to keep things fair of cource.

(020) 习题

1. enum names {WORST, WORSR, BAD, GOOD, BETTER, BEST};

2.  2,   2.333333,  2.333333

3. 输入三个整数,输出它们的平均值

[cpp] view plain copy
  1.  1 #include <iostream>  
  2.  2 using namespace std;  
  3.  3   
  4.  4 int main()  
  5.  5 {  
  6.  6     int firstScore, secondScore, thirdScore;  
  7.  7     cout << "Enter three integers: ";  
  8.  8     cin >> firstScore >> secondScore >> thirdScore;  
  9.  9     int average = (firstScore + secondScore + thirdScore) / 3;  
  10. 10     cout << average << endl;  
  11. 11     return 0;  
  12. 12 }  
wang@wang:~/test$ ./three_score 
Enter three integers: 1 2 3
2


Chapter 2: Truth, Branching, And The Game Loop: Guess My Number

(021) if (expression) statement;

[cpp] view plain copy
  1.  1 // Score Rater  
  2.  2 // Demonstrates the if statement  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 using namespace std;  
  6.  6   
  7.  7 int main()  
  8.  8 {  
  9.  9     if (true) {  
  10. 10         cout << "This is always displayd.\n";  
  11. 11     }  
  12. 12     if (false) {  
  13. 13         cout << "This is never displayed.\n";  
  14. 14     }  
  15. 15   
  16. 16     int score = 1000;  
  17. 17     if (score) {  
  18. 18         cout << "At least you didn't score zero.\n";  
  19. 19     }  
  20. 20     if (score > 250) {  
  21. 21         cout << "You scored 250 more. Decent.\n";  
  22. 22     }  
  23. 23     if (score >= 500) {  
  24. 24         cout << "You scored 500 or more. Nice.\n";  
  25. 25         if (score >= 1000) {  
  26. 26             cout << "You scored 1000 or more. Impressive!\n";  
  27. 27         }  
  28. 28     }  
  29. 29     return 0;  
  30. 30 }  
wang@wang:~/test$ g++ score_rater.cpp -o score_rater
wang@wang:~/test$ ./score_rater 
This is always displayd.
At least you didn't score zero.
You scored 250 more. Decent.
You scored 500 or more. Nice.
You scored 1000 or more. Impressive!
(022) else 语句

[cpp] view plain copy
  1.  1 // Score Rater 2.0  
  2.  2 // Demonstrates an else clause  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 using namespace std;  
  6.  6   
  7.  7 int main()  
  8.  8 {  
  9.  9     int score;  
  10. 10     cout << "Enter your score: ";  
  11. 11     cin >> score;  
  12. 12   
  13. 13     if (score >= 1000) {  
  14. 14         cout << "You scored 1000 or more. Impressive!\n";  
  15. 15     } else {  
  16. 16         cout << "You score less than 1000.\n";  
  17. 17     }  
  18. 18     return 0;  
  19. 19 }  
wang@wang:~/test$ ./score_rater2
Enter your score: 456
You score less than 1000.
(023) 多个if语句

[cpp] view plain copy
  1.  1 // Score Rater 3.0  
  2.  2 // Demonstrates if else-if else suite  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 using namespace std;  
  6.  6   
  7.  7 int main()  
  8.  8 {  
  9.  9     int score;  
  10. 10     cout << "Enter your score: ";  
  11. 11     cin >> score;  
  12. 12   
  13. 13     if (score >= 1000) {  
  14. 14         cout << "You scored 1000 or more. Impressive!\n";  
  15. 15     } else if (score >= 500) {  
  16. 16         cout << "You score 500 or more. Nice.\n";  
  17. 17     } else if (score >= 250) {  
  18. 18         cout << "You score 250 or more. Decent.\n";  
  19. 19     } else  
  20. 20         cout << "You scored less than 250. Nothing to brag about.\n";  
  21. 21     return 0;  
  22. 22 }  
wang@wang:~/test$ ./score_rater3 
Enter your score: 100
You scored less than 250. Nothing to brag about.
(024) switch语句举例

[cpp] view plain copy
  1.  1 // Menu Chooser  
  2.  2 // Demonstrates the switch statement  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 using namespace std;  
  6.  6   
  7.  7 int main()  
  8.  8 {  
  9.  9     cout << "Difficulty Levels\n";  
  10. 10     cout << "1 - Easy\n";  
  11. 11     cout << "2 - Normal\n";  
  12. 12     cout << "3 - Hard\n";  
  13. 13   
  14. 14     int choice;  
  15. 15     cout << "Choice: ";  
  16. 16     cin >> choice;  
  17. 17   
  18. 18     switch (choice) {  
  19. 19     case 1:  
  20. 20         cout << "You picked Easy.\n";  
  21. 21         break;  
  22. 22     case 2:  
  23. 23         cout << "You picked Normal.\n";  
  24. 24         break;  
  25. 25     case 3:  
  26. 26         cout << "You picked Hard.\n";  
  27. 27     default:  
  28. 28         cout << "You made an illegal choice.\n";  
  29. 29     }  
  30. 30     return 0;  
  31. 31 }  
wang@wang:~/test$ ./menu_chooser 
Difficulty Levels
1 - Easy
2 - Normal
3 - Hard
Choice: 2
You picked Normal.
(025) while 循环举例

[cpp] view plain copy
  1.  1 // Play Again  
  2.  2 // Demonstrates while loops  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 using namespace std;  
  6.  6   
  7.  7 int main()  
  8.  8 {  
  9.  9     char again = 'y';  
  10. 10     while (again == 'y') {  
  11. 11         cout << "**Played an exciting game**\n";  
  12. 12         cout << "Do you want to play again? (y/n): ";  
  13. 13         cin >> again;  
  14. 14     }  
  15. 15     cout << "Okay, bye.\n";  
  16. 16     return 0;  
  17. 17 }  
wang@wang:~/test$ ./play_again 
**Played an exciting game**
Do you want to play again? (y/n): y
**Played an exciting game**
Do you want to play again? (y/n): b
Okay, bye.
(026) do while循环

[cpp] view plain copy
  1.  1 // Play Again 2.0  
  2.  2 // Demonstrates do loops  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 using namespace std;  
  6.  6   
  7.  7 int main()  
  8.  8 {  
  9.  9     char again;  
  10. 10     do {  
  11. 11         cout << "**Played an exciting game**";  
  12. 12         cout << "\nDo you want to play again? (y/n): ";  
  13. 13         cin >> again;  
  14. 14     } while (again == 'y');  
  15. 15   
  16. 16     cout << "Okay, bye.\n";  
  17. 17     return 0;  
  18. 18 }  
wang@wang:~/test$ ./play_again2 
**Played an exciting game**
Do you want to play again? (y/n): y
**Played an exciting game**
Do you want to play again? (y/n): n
Okay, bye.
(027) break & continue

You can immediately exit a loop with the break statement, and you can jump directly to the top of a loop with a continue statement.

[cpp] view plain copy
  1.  1 // Finicky Counter  
  2.  2 // Demonstrates break and continue statements  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 using namespace std;  
  6.  6   
  7.  7 int main()  
  8.  8 {  
  9.  9     int count = 0;  
  10. 10     while (true) {  
  11. 11         count += 1;  
  12. 12         // end loop if count is greater than 10  
  13. 13         if (count > 10)  
  14. 14             break;  
  15. 15         // skip the number 5  
  16. 16         if (count == 5)  
  17. 17             continue;  
  18. 18         cout << count << endl;  
  19. 19     }  
  20. 20     return 0;  
  21. 21 }  
wang@wang:~/test$ ./finicky_counter 
1
2
3
4
6
7
8
9
10
(028) 逻辑运算符&& || !

Logical NOT, ! has a higher level of precedence that logical AND, &&, which has a higher precedence than logical OR, ||.

[cpp] view plain copy
  1.  1 // Designers Network  
  2.  2 // Demonstrates logical operators  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 #include <string>  
  6.  6   
  7.  7 using namespace std;  
  8.  8   
  9.  9 int main()  
  10. 10 {  
  11. 11     string username;  
  12. 12     string password;  
  13. 13     bool success;  
  14. 14     cout << "\tGame Designer's Network\n";  
  15. 15     do {  
  16. 16         cout << "Username: ";  
  17. 17         cin >> username;  
  18. 18         cout << "Password: ";  
  19. 19         cin >> password;  
  20. 20   
  21. 21         if (username == "S.Meier" && password == "civilization") {  
  22. 22             cout << "Hey, Sid.\n";  
  23. 23             success = true;  
  24. 24         } else if (username == "S.Miyamoto" && password == "mariobros") {  
  25. 25             cout << "What's up, Shigegu?\n";  
  26. 26             success = true;  
  27. 27         } else if (username == "guest" || password == "guest") {  
  28. 28             cout << "Welcome, guest.\n";  
  29. 29             success = true;  
  30. 30         } else {  
  31. 31             cout << "Your login failed.\n";  
  32. 32             success = false;  
  33. 33         }  
  34. 34     } while (!success);  
  35. 35     return 0;  
  36. 36 }  
wang@wang:~/test$ ./designers_network 
    Game Designer's Network
Username: wang
Password: wang
Your login failed.
Username: wang
Password: guest
Welcome, guest.
(029) 产生随机数

The file sctdlib contains (among other things) functions that deal with generating random numbers.

The upper limit is stored in the constant RAND_MAX.

In terms of the actual code, the srand() function seeds the random number generator.

[cpp] view plain copy
  1.  1 // Die Roller  
  2.  2 // Demonstrates generating random numbers  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 #include <cstdlib>  
  6.  6 #include <ctime>  
  7.  7 using namespace std;  
  8.  8   
  9.  9 int main()  
  10. 10 {  
  11. 11     // seed random number generator  
  12. 12     srand(static_cast<unsigned int> (time(0)));  
  13. 13     int randomNumber = rand();  
  14. 14     // get a number between 1 and 6  
  15. 15     int die = (randomNumber % 6) + 1;  
  16. 16     cout << "You rolled a " << die << endl;  
  17. 17     return 0;  
  18. 18 }  
wang@wang:~/test$ ./die_roller 
You rolled a 3
wang@wang:~/test$ ./die_roller 
You rolled a 3
wang@wang:~/test$ ./die_roller 
You rolled a 6
(030) 猜数字游戏,适合三岁小孩子玩。

[cpp] view plain copy
  1.  1 // Guess My Number  
  2.  2 // The classic number guessing game  
  3.  3 #include <iostream>  
  4.  4 #include <cstdlib>  
  5.  5 #include <ctime>  
  6.  6 using namespace std;  
  7.  7   
  8.  8 int main()  
  9.  9 {  
  10. 10     // seed random  
  11. 11     srand(static_cast<unsigned int>(time(0)));  
  12. 12     // random number between 1 and 100  
  13. 13     int secretNumber = rand() % 100 + 1;  
  14. 14     int tries = 0;  
  15. 15     int guess;  
  16. 16     cout << "\tWelcome to Guess My Number\n";  
  17. 17     do {  
  18. 18         cout << "Enter a guess: ";  
  19. 19         cin >> guess;  
  20. 20         ++tries;  
  21. 21         if (guess > secretNumber)  
  22. 22             cout << "Too high!\n";  
  23. 23         else if (guess < secretNumber)  
  24. 24             cout << "Too low!\n";  
  25. 25         else  
  26. 26             cout << "That's it! you got it in " << tries << " guesses!\n";  
  27. 27     } while (guess != secretNumber);  
  28. 28     return 0;  
  29. 29 }  
wang@wang:~/test$ ./guess_my_number 
    Welcome to Guess My Number
Enter a guess: 56
Too high!
Enter a guess: 28
Too high!
Enter a guess: 14
Too high!
Enter a guess: 8
Too high!
Enter a guess: 4
Too high!
Enter a guess: 2
Too low!
Enter a guess: 3
That's it! you got it in 7 guesses!

(031) 习题

1. 使用enum表示。

[cpp] view plain copy
  1.  1 #include <iostream>  
  2.  2 using namespace std;  
  3.  3   
  4.  4 int main()  
  5.  5 {  
  6.  6     cout << "Difficult Levels\n";  
  7.  7     cout << "1 - Easy\n";  
  8.  8     cout << "2 - Normal\n";  
  9.  9     cout << "3 - Hard\n";  
  10. 10     enum level {EASY = 1, NORMAL, HARD};  
  11. 11     int choice;  
  12. 12     cout << "Choice: ";  
  13. 13     cin >> choice;  
  14. 14     switch (choice) {  
  15. 15     case EASY:  
  16. 16         cout << "You picked Easy.\n";  
  17. 17         break;  
  18. 18     case NORMAL:  
  19. 19         cout << "You picked Normal.\n";  
  20. 20         break;  
  21. 21     case HARD:  
  22. 22         cout << "You picked Hard.\n";  
  23. 23     default:  
  24. 24         cout << "You made an illegal choice.\n";  
  25. 25     }  
  26. 26     return 0;  
  27. 27 }  
wang@wang:~/test$ ./menulevel 
Difficult Levels
1 - Easy
2 - Normal
3 - Hard
Choice: 2
You picked Normal.

2. 没有进入while循环中。

3. 用户提供数据,电脑猜

[cpp] view plain copy
  1.  1 // Guess My Number  
  2.  2 // The classic number guessing game  
  3.  3 #include <iostream>  
  4.  4 #include <cstdlib>  
  5.  5 #include <ctime>  
  6.  6 using namespace std;  
  7.  7   
  8.  8 int main()  
  9.  9 {  
  10. 10     int number;  
  11. 11     cout << "Enter a number (1 - 10): ";  
  12. 12     cin >> number;  
  13. 13     int tries = 0;  
  14. 14     int guess;  
  15. 15     cout << "\tWelcome to Guess My Number\n";  
  16. 16     do {  
  17. 17         // seed random  
  18. 18         srand(static_cast<unsigned int>(time(0)));  
  19. 19         // random number between 1 and 10  
  20. 20         guess = rand() % 10 + 1;  
  21. 21         ++tries;  
  22. 22         if (guess > number)  
  23. 23             cout << "Too high!\n";  
  24. 24         else if (guess < number)  
  25. 25             cout << "Too low!\n";  
  26. 26         else  
  27. 27             cout << "That's it! you got it in " << tries << " guesses!\n";  
  28. 28     } while (guess != number);  
  29. 29     return 0;  
  30. 30 }  
随机猜猜的次数太多。

That's it! you got it in 300166 guesses!


Chapter 3: For Loops, Strings, And Arrays: Word Jumble

(032) for循环

[cpp] view plain copy
  1.  1 // Counter  
  2.  2 // Demonstrates for loops  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 using namespace std;  
  6.  6   
  7.  7 int main()  
  8.  8 {  
  9.  9     cout << "Count forward: ";  
  10. 10     for (int i = 0; i < 10; ++i)  
  11. 11         cout << i << " ";  
  12. 12     cout << "\nCounting backward: ";  
  13. 13     for (int i = 9; i >= 0; --i)  
  14. 14         cout << i << " ";  
  15. 15     cout << "\nCounting by fives: ";  
  16. 16     for (int i = 0; i <= 50; i += 5)  
  17. 17         cout << i << " ";  
  18. 18     cout << "\nCounting with null statements: ";  
  19. 19     int count = 0;  
  20. 20     for (; count < 10;) {  
  21. 21         cout << count << " ";  
  22. 22         ++count;  
  23. 23     }  
  24. 24     cout << "\nCounting with nested for loops:\n";  
  25. 25     const int ROWS = 5;  
  26. 26     const int COLUMNS = 3;  
  27. 27     for (int i = 0; i < ROWS; ++i) {  
  28. 28         for (int j = 0; j < COLUMNS; ++j) {  
  29. 29             cout << i << "," << j << "  ";  
  30. 30         }  
  31. 31         cout << endl;  
  32. 32     }  
  33. 33     return 0;  
  34. 34 }  
wang@wang:~/test$ ./counter 
Count forward: 0 1 2 3 4 5 6 7 8 9 
Counting backward: 9 8 7 6 5 4 3 2 1 0 
Counting by fives: 0 5 10 15 20 25 30 35 40 45 50 
Counting with null statements: 0 1 2 3 4 5 6 7 8 9 
Counting with nested for loops:
0,0  0,1  0,2  
1,0  1,1  1,2  
2,0  2,1  2,2  
3,0  3,1  3,2  
4,0  4,1  4,2 

(033) string 对象的用法

string 几种不同的初始化方式。

earse第一个参数是位置,第二个参数是个数。

When using find(), you can supply an optional argument that specifies a character number for the program to start looking for the substring.

[cpp] view plain copy
  1.  1 // String Tester  
  2.  2 // Demonstrates string objects  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 #include <string>  
  6.  6 using namespace std;  
  7.  7   
  8.  8 int main()  
  9.  9 {  
  10. 10     string word1 = "Game";  
  11. 11     string word2("Over");  
  12. 12     string word3(3, '!');  
  13. 13   
  14. 14     string phrase = word1 + " " + word2 + word3;  
  15. 15     cout << "The phrase is: " << phrase << "\n";  
  16. 16     cout << "The phrase has " << phrase.size() << " characters in it.\n";  
  17. 17     cout << "The character at position 0 is: " << phrase[0] << "\n";  
  18. 18     cout << "Changing the character at position 0.\n";  
  19. 19     phrase[0] = 'L';  
  20. 20     cout << "The phrase is now: " << phrase << "\n";  
  21. 21     for (unsigned int i = 0; i < phrase.size(); ++i)  
  22. 22         cout << "Character at position " << i << " is: " << phrase[i] << "\n";  
  23. 23     cout << "The sequence 'Over' begins at location ";  
  24. 24     cout << phrase.find("Over") << endl;  
  25. 25     if (phrase.find("eggplant") == string::npos)  
  26. 26         cout << "'eggplant' is not in the phrase.\n";  
  27. 27     phrase.erase(4, 5);  
  28. 28     cout << "The phrase is now: " << phrase << endl;  
  29. 29     phrase.erase(4);  
  30. 30     cout << "The phrase is now: " << phrase << endl;  
  31. 31     phrase.erase();  
  32. 32     cout << "The phrase is now: " << phrase << endl;  
  33. 33     if (phrase.empty())  
  34. 34         cout << "The phrase is no more.\n";  
  35. 35     return 0;  
  36. 36 }  
wang@wang:~/test$ ./string_tester 
The phrase is: Game Over!!!
The phrase has 12 characters in it.
The character at position 0 is: G
Changing the character at position 0.
The phrase is now: Lame Over!!!
Character at position 0 is: L
Character at position 1 is: a
Character at position 2 is: m
Character at position 3 is: e
Character at position 4 is:  
Character at position 5 is: O
Character at position 6 is: v
Character at position 7 is: e
Character at position 8 is: r
Character at position 9 is: !
Character at position 10 is: !
Character at position 11 is: !
The sequence 'Over' begins at location 5
'eggplant' is not in the phrase.
The phrase is now: Lame!!!
The phrase is now: Lame
The phrase is now: 
The phrase is no more.
(034) 英雄复仇游戏

主要讲述携带的装备情况

[cpp] view plain copy
  1.  1 // Hero's Inventory  
  2.  2 // Demonstrates arrays  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 #include <string>  
  6.  6 using namespace std;  
  7.  7   
  8.  8 int main()  
  9.  9 {  
  10. 10     const int MAX_ITEMS = 10;  
  11. 11     string inventory[MAX_ITEMS];  
  12. 12     int numItems = 0;  
  13. 13     inventory[numItems++] = "sword";  
  14. 14     inventory[numItems++] = "armor";  
  15. 15     inventory[numItems++] = "shield";  
  16. 16     cout << "Your items:\n";  
  17. 17     for (int i = 0; i < numItems; i++)  
  18. 18         cout << inventory[i] << endl;  
  19. 19     cout << "You trade your sword for a battle axe.\n";  
  20. 20     inventory[0] = "battle axe";  
  21. 21     for (int i = 0; i < numItems; ++i)  
  22. 22         cout << inventory[i] << endl;  
  23. 23     cout << "The item name '" << inventory[0] << "' has ";  
  24. 24     cout << inventory[0].size() << " letters in it.\n";  
  25. 25     cout << "You find a healing potion.\n";  
  26. 26     if (numItems < MAX_ITEMS)  
  27. 27         inventory[numItems++] = "healing portion";  
  28. 28     else  
  29. 29         cout << "You have too many items and can't carry another.\n";  
  30. 30     for (int i = 0; i < numItems; ++i)  
  31. 31         cout << inventory[i] << endl;  
  32. 32     return 0;  
  33. 33 }  
wang@wang:~/test$ ./heros_inventory 
Your items:
sword
armor
shield
You trade your sword for a battle axe.
battle axe
armor
shield
The item name 'battle axe' has 10 letters in it.
You find a healing potion.
battle axe
armor
shield
healing portion

(035) index check

Testing to make sure that an index number is a valid array position before using it is called bounds checking.

(036) tic-tac-toe游戏

[cpp] view plain copy
  1.  1 // Tic-Tac-Toe Board  
  2.  2 // Demonstrates multidimensional arrays  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 using namespace std;  
  6.  6   
  7.  7 int main()  
  8.  8 {  
  9.  9     const int ROWS = 3;  
  10. 10     const int COLUMNS = 3;  
  11. 11     char board[ROWS][COLUMNS] = {{'O''X''O'}, {' ''X''X'}, {'X''O''O'}};  
  12. 12     cout << "Here's the tic-tac-toe board:\n";  
  13. 13     for (int i = 0; i < ROWS; i++) {  
  14. 14         for (int j = 0; j < COLUMNS; ++j)  
  15. 15             cout << board[i][j];  
  16. 16         cout << endl;  
  17. 17     }  
  18. 18     cout << "'X' moves to the empty location.\n";  
  19. 19     board[1][0] = 'X';  
  20. 20     cout << "Now the tic-tac-toe board is:\n";  
  21. 21     for (int i = 0; i < ROWS; i++) {  
  22. 22         for(int j = 0; j < COLUMNS; ++j)  
  23. 23             cout << board[i][j];  
  24. 24         cout << endl;  
  25. 25     }  
  26. 26     cout << "'X' wins!\n";  
  27. 27     return 0;  
  28. 28 }  
wang@wang:~/test$ ./tic-tac-toe_board 
Here's the tic-tac-toe board:
OXO
 XX
XOO
'X' moves to the empty location.
Now the tic-tac-toe board is:
OXO
XXX
XOO
'X' wins!
(037) 猜字游戏

把单词打乱,然后根据提示猜是什么单词。

[cpp] view plain copy
  1. // Word Jumble  
  2. // The classic word jumble game where the player can ask for a hint  
  3. #include <iostream>  
  4. #include <string>  
  5. #include <cstdlib>  
  6. #include <ctime>  
  7. using namespace std;  
  8.   
  9. int main()  
  10. {  
  11.     enum field {WORD, HINT, NUM_FIELDS};  
  12.     const int NUM_WORDS = 5;  
  13.     const string WORDS[NUM_WORDS][NUM_FIELDS] = {  
  14.         {"wall""Do you feel you're banging your head against something?"},  
  15.         {"glasses""These might help you see the answer."},  
  16.         {"labored""Going slowly, is it?"},  
  17.         {"persistent""Keep at it."},  
  18.         {"jumble""It's what the game is all about."}};  
  19.     srand(static_cast<unsigned int>(time(0)));  
  20.     int choice = rand() % NUM_WORDS;  
  21.     string theWord = WORDS[choice][WORD];  
  22.     string theHint = WORDS[choice][HINT];  
  23.     // jumbled version of word  
  24.     string jumble = theWord;  
  25.     int length = jumble.size();  
  26.     for (int i = 0; i < length; ++i) {  
  27.         int index1 = (rand() % length);  
  28.         int index2 = (rand() % length);  
  29.         char temp = jumble[index1];  
  30.         jumble[index1] = jumble[index2];  
  31.         jumble[index2] = temp;  
  32.     }  
  33.     cout << "\t\tWelcome to Word Jumble!\n";  
  34.     cout << "Unscramble the letters to make a word.\n";  
  35.     cout << "Enter 'hint' for a hint.\n";  
  36.     cout << "Enter 'quit' to quit the game.\n";  
  37.     cout << "The jumble is: " << jumble;  
  38.     string guess;  
  39.     cout << "\nyou guess: ";  
  40.     cin >> guess;  
  41.     while ((guess != theWord) && (guess != "quit")) {  
  42.         if(guess == "hint")  
  43.             cout << theHint;  
  44.         else  
  45.             cout << "Sorry, that's not it.";  
  46.         cout << "\nYour guess: ";  
  47.         cin >> guess;  
  48.     }  
  49.     if (guess == theWord)  
  50.         cout << "That's it! You guess it!\n";  
  51.     cout << "Thanks for playing.\n";  
  52.     return 0;  
  53. }  
wang@wang:~/test$ ./word_jumble 
        Welcome to Word Jumble!
Unscramble the letters to make a word.
Enter 'hint' for a hint.
Enter 'quit' to quit the game.
The jumble is: eetpsitsnr
you guess: hint
Keep at it.
Your guess: persistent
That's it! You guess it!
Thanks for playing.
(038) 对象

Objects are encapsulated, cohesive entities that combine data (called data members) and functions (called member functions).

(039) 习题

1. 增加计数的效果

[cpp] view plain copy
  1. cin >> guess;  
  2.  41     int count = 1;  
  3.  42     while ((guess != theWord) && (guess != "quit")) {  
  4.  43         if(guess == "hint")  
  5.  44             cout << theHint;  
  6.  45         else  
  7.  46             cout << "Sorry, that's not it.";  
  8.  47         cout << "\nYour guess: ";  
  9.  48         cin >> guess;  
  10.  49         ++count;  
  11.  50     }  
2. 数组访问会越界

i < phrase.size();

3. char board[ROWS][COLUMNS]; 


Chapter 4: The Standard Template Library: Hangman

(040) 标准库

The STL(Standard Template Library) represents a powerful collection of programming work that's been done well.

(041) 使用vector举例

[html] view plain copy
  1.  1 // Hero's Inventory 2.0  
  2.  2 // Demonstrates vectors  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 #include <string>  
  6.  6 #include <vector>  
  7.  7 using namespace std;  
  8.  8   
  9.  9 int main()  
  10. 10 {  
  11. 11     vector<string> inventory;  
  12. 12     inventory.push_back("sword");  
  13. 13     inventory.push_back("armor");  
  14. 14     inventory.push_back("shield");  
  15. 15     cout << "You have " << inventory.size() << " items.\n";  
  16. 16     cout << "Your items:\n";  
  17. 17     for (unsigned int i = 0; i < inventory.size(); ++i)  
  18. 18         cout << inventory[i] << endl;  
  19. 19     cout << "You trade your sword for a battle axe.";  
  20. 20     inventory[0] = "battle axe";  
  21. 21     cout << "Your items:\n";  
  22. 22     for (unsigned int i = 0; i < inventory.size(); ++i)  
  23. 23         cout << inventory[i] << endl;  
  24. 24     cout << "The item name '" << inventory[0] << "' has ";  
  25. 25     cout << inventory[0].size() << " letters in it.\n";  
  26. 26     cout << "your shield is destroyed in a fierce battle.";  
  27. 27     inventory.pop_back();  
  28. 28     cout << "Your items:\n";  
  29. 29     for (unsigned int i = 0; i < inventory.size(); ++i)  
  30. 30         cout << inventory[i] << endl;  
  31. 31     cout << "You were robbed of all of your possessions by a thief.\n";  
  32. 32     inventory.clear();  
  33. 33     if (inventory.empty())  
  34. 34         cout << "You have nothing.\n";  
  35. 35     else  
  36. 36         cout << "You have at least one item.\n";  
  37. 37     return 0;  
  38. 38 }  
wang@wang:~/workspace/beginc++game$ ./heros_inventory2 
You have 3 items.
Your items:
sword
armor
shield
You trade your sword for a battle axe.Your items:
battle axe
armor
shield
The item name 'battle axe' has 10 letters in it.
your shield is destroyed in a fierce battle.Your items:
battle axe
armor
You were robbed of all of your possessions by a thief.
You have nothing.

(042) 迭代器举例

[cpp] view plain copy
  1.  1 // Hero's Inventory 3.0  
  2.  2 // Demonstrates iterators  
  3.  3 #include <iostream>  
  4.  4 #include <string>  
  5.  5 #include <vector>  
  6.  6 using namespace std;  
  7.  7   
  8.  8 int main()  
  9.  9 {  
  10. 10     vector<string> inventory;  
  11. 11     inventory.push_back("sword");  
  12. 12     inventory.push_back("armor");  
  13. 13     inventory.push_back("shield");  
  14. 14     vector<string>::iterator myIterator;  
  15. 15     vector<string>::const_iterator iter;  
  16. 16     cout << "Your items:\n";  
  17. 17     for (iter = inventory.begin(); iter != inventory.end(); ++iter)  
  18. 18         cout << *iter << endl;  
  19. 19     cout << "You trade your sword for a battle axe.\n";  
  20. 20     myIterator = inventory.begin();  
  21. 21     *myIterator = "battle axe";  
  22. 22     cout << "Your items:\n";  
  23. 23     for (iter = inventory.begin(); iter != inventory.end(); ++iter)  
  24. 24         cout << *iter << endl;  
  25. 25     cout << "The item name '" << *myIterator << "' has ";  
  26. 26     cout << (*myIterator).size() << " letters in it.\n";  
  27. 27     cout << "The item name '" << *myIterator << "' has ";  
  28. 28     cout << myIterator->size() << " letters in it.\n";  
  29. 29     cout << "You recover a corssbox from a slain enemy.\n";  
  30. 30     inventory.insert(inventory.begin(), "crossbox");  
  31. 31     cout << "Your items:\n";  
  32. 32     for (iter = inventory.begin(); iter != inventory.end(); ++iter)  
  33. 33         cout << *iter << endl;  
  34. 34     cout << "Your armor is destoryed in a fierce battle.\n";  
  35. 35     inventory.erase(inventory.begin() + 2);  
  36. 36     cout << "Your items:\n";  
  37. 37     for (iter = inventory.begin(); iter != inventory.end(); ++iter)  
  38. 38         cout << *iter << endl;  
  39. 39     return 0;  
  40. 40 }  
wang@wang:~/test$ ./heros_inventory3 
Your items:
sword
armor
shield
You trade your sword for a battle axe.
Your items:
battle axe
armor
shield
The item name 'battle axe' has 10 letters in it.
The item name 'battle axe' has 10 letters in it.
You recover a corssbox from a slain enemy.
Your items:
crossbox
battle axe
armor
shield
Your armor is destoryed in a fierce battle.
Your items:
crossbox
battle axe
shield
(043) insert方法

One form of the insert() member function inserts a new element into a vector just before the element referred to by a given iterator.

(044) 算法举例

The random_shuffle() algorithm randomizes the elements of a sequence.

The sort() algorithm sorts the elements of a sequence in ascending order.

[cpp] view plain copy
  1.  1 // High Scores  
  2.  2 // Demonstrates algorithms  
  3.  3 #include <iostream>  
  4.  4 #include <vector>  
  5.  5 #include <algorithm>  
  6.  6 #include <ctime>  
  7.  7 #include <cstdlib>  
  8.  8 using namespace std;  
  9.  9   
  10. 10 int main()  
  11. 11 {  
  12. 12     vector<int>::const_iterator iter;  
  13. 13     cout << "Creating a list of scores.\n";  
  14. 14     vector<int> scores;  
  15. 15     scores.push_back(1500);  
  16. 16     scores.push_back(3500);  
  17. 17     scores.push_back(7500);  
  18. 18   
  19. 19     cout << "High Scores:\n";  
  20. 20     for (iter = scores.begin(); iter != scores.end(); ++iter)  
  21. 21         cout << *iter << endl;  
  22. 22     cout << "Finding a score:\n";  
  23. 23     int score;  
  24. 24     cout << "Enter a score to find: ";  
  25. 25     cin >> score;  
  26. 26     iter = find(scores.begin(), scores.end(), score);  
  27. 27     if (iter != scores.end())  
  28. 28         cout << "Score found.\n";  
  29. 29     else  
  30. 30         cout << "Score not found.\n";  
  31. 31     cout << "Randomizing scores.\n";  
  32. 32     srand(static_cast<unsigned int>(time(0)));  
  33. 33     random_shuffle(scores.begin(), scores.end());  
  34. 34     cout << "High Scores:\n";  
  35. 35     for (iter = scores.begin(); iter != scores.end(); ++iter)  
  36. 36         cout << *iter << endl;  
  37. 37     cout << "Sorting scores.\n";  
  38. 38     sort(scores.begin(), scores.end());  
  39. 39     cout << "High Scores:\n";  
  40. 40     for (iter = scores.begin(); iter != scores.end(); ++iter)  
  41. 41         cout << *iter << endl;  
  42. 42     return 0;  
  43. 43 }  
wang@wang:~/test$ ./high_scores 
Creating a list of scores.
High Scores:
1500
3500
7500
Finding a score:
Enter a score to find: 7500
Score found.
Randomizing scores.
High Scores:
7500
3500
1500
Sorting scores.
High Scores:
1500
3500
7500
(045) 标注库提供的所有容器

deque                   Sequential                    Double-ended queue

list                          Sequential                    Linear list

map                       Associative                   Collection of key/value pairs in which each key is associated with exactly one value

multimap              Associative                   Collection of key/value pairs in which each key may be associated with more than one value

multiset                 Associative                   Collection in which each element is not necessarily unique

priority_queue     Adaptor                         Priority queue

queue                    Adaptor                         Queue

set                           Associative                  Collection in which each element is unique

stack                       Adaptor                        Stack

vector                     Sequential                   Dynamic array

(046) Pseudocode伪代码

需要很好的英语基础。

Many programmers sketch out their programs using pseudocode - a language that falls somewhere between English and a formal programming language.

By taking each step described in pseudocode and breaking it down into series of simpler steps, the plan becomes closer to programming code.

(047) 伪代码举例

比较经典的例子,猜字游戏,只有八次机会;

刚开始的时候可以乱猜,后来根据已知的字符猜未知的字符。

[cpp] view plain copy
  1. /* 
  2.  * Pseudocode 
  3.  * Create a group of words 
  4.  * Pick a random word from the group as the secret word 
  5.  * While player hasn't made too many incorrect guesses and hasn't 
  6.  * guessed the secret word 
  7.  *      Tell player how many incorrect guesses he or she has left 
  8.  *      Show player the letters he or she has guessed 
  9.  *      Show player how much of the secret word he or she has guessed 
  10.  *      Get player's next guess 
  11.  *      While player has entered a letter that he has already guessed 
  12.  *          Get player's guess 
  13.  *      Add the new guess to the group of used letters 
  14.  *      If the guess is in the secret word 
  15.  *          Tell the player the guess is correct 
  16.  *          Update the word guessed so far with the new letter 
  17.  *      Otherwise 
  18.  *          Tell the player the guess is incorrect 
  19.  * made 
  20.  * If the player has made too many incorrect guesses 
  21.  *      Tell the player that he or she has been hanged 
  22.  * Otherwise 
  23.  *      Congratulate the player on guessing the secret word 
  24.  */  
  25.   
  26. // Hangman  
  27. // The classic game of hangman  
  28. #include <iostream>  
  29. #include <string>  
  30. #include <vector>  
  31. #include <algorithm>  
  32. #include <ctime>  
  33. #include <cctype>  
  34.   
  35. using namespace std;  
  36.   
  37. int main(int argc, char *argv[])  
  38. {  
  39.     // setup  
  40.     // maximum number of incorrect guesses allowed  
  41.     const int MAX_WRONG = 8;  
  42.     vector<string> words;  
  43.     words.push_back("GUESS");  
  44.     words.push_back("HANGMAN");  
  45.     words.push_back("DIFFICULT");  
  46.     srand(static_cast<unsigned int>(time(0)));  
  47.     random_shuffle(words.begin(), words.end());  
  48.     const string THE_WORD = words[0];  
  49.     // number of incorrect guesses  
  50.     int wrong = 0;  
  51.     // word guessed so far  
  52.     string soFar(THE_WORD.size(), '-');  
  53.     // letters already guessed  
  54.     string used = "";  
  55.   
  56.     cout << "Welcome to Hangman. Good luck!\n";  
  57.   
  58.     // main loop  
  59.     while ((wrong < MAX_WRONG) && (soFar != THE_WORD)) {  
  60.         cout << "You have " << (MAX_WRONG - wrong) << " incorrect guesses left.\n";  
  61.         cout << "You have used the following letters: " << used << endl;  
  62.         cout << "So far, the word is: " << soFar << endl;  
  63.         char guess;  
  64.         cout << "Enter your guess: ";  
  65.         cin >> guess;  
  66.         // make uppercase since secret word in uppercase  
  67.         guess = toupper(guess);  
  68.         while (used.find(guess) != string::npos) {  
  69.             cout << "You have already guessed " << guess << endl;  
  70.             cout << "Enter your guess: ";  
  71.             cin >> guess;  
  72.             guess = toupper(guess);  
  73.         }  
  74.         used += guess;  
  75.         if (THE_WORD.find(guess) != string::npos) {  
  76.             cout << "That's right! " << guess << " is in the word.\n";  
  77.             // update soFar to include newly guessed letter  
  78.             for (int i = 0; i < THE_WORD.size(); ++i)  
  79.                 if (THE_WORD[i] == guess)  
  80.                     soFar[i] = guess;  
  81.         } else {  
  82.             cout << "Sorry, " << guess << " isn't in the word.\n";  
  83.             ++wrong;  
  84.         }  
  85.     }  
  86.     // shut down  
  87.     if (wrong == MAX_WRONG)  
  88.         cout << "You have been hanged!\n";  
  89.     else  
  90.         cout << "You guess it!\n";  
  91.     cout << "The word was " << THE_WORD << endl;  
  92.   
  93.     return 0;  
  94. }  

Welcome to Hangman. Good luck!
You have 8 incorrect guesses left.
You have used the following letters: 
So far, the word is: -------
Enter your guess: a
That's right! A is in the word.
You have 8 incorrect guesses left.
You have used the following letters: A
So far, the word is: -A---A-
Enter your guess: h
That's right! H is in the word.
You have 8 incorrect guesses left.
You have used the following letters: AH
So far, the word is: HA---A-
Enter your guess: n
That's right! N is in the word.
You have 8 incorrect guesses left.
You have used the following letters: AHN
So far, the word is: HAN--AN
Enter your guess: g
That's right! G is in the word.
You have 8 incorrect guesses left.
You have used the following letters: AHNG
So far, the word is: HANG-AN
Enter your guess: m
That's right! M is in the word.
You guess it!
The word was HANGMAN

(048) 习题

1. 编写vector包括你喜欢的游戏

[cpp] view plain copy
  1.  1 #include <algorithm>  
  2.  2 #include <iostream>  
  3.  3 #include <vector>  
  4.  4 using namespace std;  
  5.  5   
  6.  6 int main()  
  7.  7 {  
  8.  8     vector<string> games;  
  9.  9     vector<string>::iterator iter;  
  10. 10     games.push_back("war world");  
  11. 11     games.push_back("person vender");  
  12. 12     iter = games.begin();  
  13. 13     games.insert(iter, "hello world");  
  14. 14     for (iter = games.begin(); iter != games.end(); ++iter)  
  15. 15         cout << *iter << endl;  
  16. 16     return 0;  
  17. 17 }  
wang@wang:~/test$ ./list_game 
hello world
war world
person vender
2. 每次都是调过一个数据,没有每个都遍历

3. 伪代码,写得不好。

get some words and introduction about every word.
choose one word in random.
jumble the word.
guess the word
    if word equal quit, exit the game
    if word equal hint, give the word introduction
if guess equal the word
    you success


Chapter 5: Functions: Mad Lib

(049) 函数简单举例

[cpp] view plain copy
  1.  1 // Instructions  
  2.  2 // Demonstrates writing new functions  
  3.  3 #include <iostream>  
  4.  4 using namespace std;  
  5.  5   
  6.  6 // function prototype (declaration)  
  7.  7 void instruction();  
  8.  8   
  9.  9 int main()  
  10. 10 {  
  11. 11     instruction();  
  12. 12     return 0;  
  13. 13 }  
  14. 14   
  15. 15 // function definition  
  16. 16 void instruction() {  
  17. 17     cout << "Welcome to the most fun you've ever had with text!\n";  
  18. 18     cout << "Here's how to play the game...\n";  
  19. 19 }  
wang@wang:~/test$ ./instructions 
Welcome to the most fun you've ever had with text!
Here's how to play the game...

(050)  第二个例子,传递参数

[cpp] view plain copy
  1.  1 // Yes or No  
  2.  2 // Demonstrates return values and parameters  
  3.  3   
  4.  4 #include <iostream>  
  5.  5 #include <string>  
  6.  6 using namespace std;  
  7.  7   
  8.  8 char askYesNo1();  
  9.  9 char askYesNo2(string question);  
  10. 10   
  11. 11 int main()  
  12. 12 {  
  13. 13     char answer1 = askYesNo1();  
  14. 14     cout << "Thank you for answering: " << answer1 << "\n";  
  15. 15     char answer2 = askYesNo2("Do you wish to save your game?");  
  16. 16     cout << "Thanks for answering: " << answer2 << "\n";  
  17. 17     return 0;  
  18. 18 }  
  19. 19   
  20. 20 char askYesNo1() {  
  21. 21     char response1;  
  22. 22     do {  
  23. 23         cout << "Please enter 'y' or 'n': ";  
  24. 24         cin >> response1;  
  25. 25     } while(response1 != 'y' && response1 != 'n');  
  26. 26     return response1;  
  27. 27 }  
  28. 28   
  29. 29 char askYesNo2(string question) {  
  30. 30     char response2;  
  31. 31     do {  
  32. 32         cout << question << " (y/n): ";  
  33. 33         cin >> response2;  
  34. 34     } while (response2 != 'y' && response2 != 'n');  
  35. 35     return response2;  
  36. 36 }  
wang@wang:~/test$ ./yes_or_no 
Please enter 'y' or 'n': n
Thank you for answering: n
Do you wish to save your game? (y/n): y
Thanks for answering: y
(051) 不要做别人重复的工作

It's always a waste of time to reinvent the wheel.

Increased company productivity.

Improved software quality.

Improved software performance.

(052) 变量空间

Every time you use curly braces to create a block, you create a scope.

[cpp] view plain copy
  1.  1 // Scoping  
  2.  2 // Demonstrates scopes  
  3.  3 #include <iostream>  
  4.  4 using namespace std;  
  5.  5 void func();  
  6.  6 int main()  
  7.  7 {  
  8.  8     // local variable in main  
  9.  9     int var = 5;  
  10. 10     cout << "In main() var is: " << var << "\n";  
  11. 11     func();  
  12. 12     cout << "Back in main() var is: " << var << endl;  
  13. 13     {  
  14. 14         cout << "In main() in a new scope var is: " << var << endl;  
  15. 15         cout << "Creating new var in new scope.\n";  
  16. 16         // variable in new scope, hides other variable named var  
  17. 17         int var = 10;  
  18. 18         cout << "In main() in a new scope var is: " << var << "\n";  
  19. 19     }  
  20. 20     cout << "At end of main() var created in new scope no longer exists.\n";  
  21. 21     cout << "At end of main() var is: " << var << "\n";  
  22. 22     return 0;  
  23. 23 }  
  24. 24   
  25. 25 void func()  
  26. 26 {  
  27. 27     int var = -5;  
  28. 28     cout << "In func() var is: " << var << "\n";  
  29. 29 }  
wang@wang:~/test$ ./scoping 
In main() var is: 5
In func() var is: -5
Back in main() var is: 5
In main() in a new scope var is: 5
Creating new var in new scope.
In main() in a new scope var is: 10
At end of main() var created in new scope no longer exists.
At end of main() var is: 5
(053) 全局变量举例

[cpp] view plain copy
  1.  1 // Global Reach  
  2.  2 // Demonstrates global variables  
  3.  3 #include <iostream>  
  4.  4 using namespace std;  
  5.  5 // global variable  
  6.  6 int glob = 10;  
  7.  7 void access_global();  
  8.  8 void hide_global();  
  9.  9 void change_global();  
  10. 10 int main()  
  11. 11 {  
  12. 12     cout << "In main() glob is: " << glob << "\n";  
  13. 13     access_global();  
  14. 14     hide_global();  
  15. 15     cout << "In main() glob is: " << glob << endl;  
  16. 16     change_global();  
  17. 17     cout << "In main() glob is: " << glob << endl;  
  18. 18     return 0;  
  19. 19 }  
  20. 20   
  21. 21 void access_global() {  
  22. 22     cout << "In access_global() glob is: " << glob << endl;  
  23. 23 }  
  24. 24   
  25. 25 void hide_global() {  
  26. 26     // hide global variable glob  
  27. 27     int glob = 0;  
  28. 28     cout << "In hide_global() glob is: " << glob << endl;  
  29. 29 }  
  30. 30   
  31. 31 void change_global() {  
  32. 32     glob = -10;  
  33. 33     cout << "In change_global() glob is: " << glob << "\n";  
  34. 34 }  
wang@wang:~/test$ ./global_reach 
In main() glob is: 10
In access_global() glob is: 10
In hide_global() glob is: 0
In main() glob is: 10
In change_global() glob is: -10
In main() glob is: -10
(054) 常量全局变量

Unlike global variables, which can make your programs confusing, global constants -- constants that can be accessed from anywhere in your program -- can help make programs clearer.

(055) 默认参数

[cpp] view plain copy
  1.  1 // Give me a Number  
  2.  2 // Demonsrates default function arguments  
  3.  3 #include <iostream>  
  4.  4 #include <string>  
  5.  5 using namespace std;  
  6.  6   
  7.  7 int askNumber(int high, int low = 1);  
  8.  8   
  9.  9 int main()  
  10. 10 {  
  11. 11     int number = askNumber(5);  
  12. 12     cout << "Thanks for entering: " << number << "\n";  
  13. 13     number = askNumber(10, 5);  
  14. 14     cout << "Thanks for entering: " << number << "\n";  
  15. 15     return 0;  
  16. 16 }  
  17. 17   
  18. 18 int askNumber(int high, int low) {  
  19. 19     int num;  
  20. 20     do {  
  21. 21         cout << "Please enter a number (" << low << " - " << high << "): ";  
  22. 22         cin >> num;  
  23. 23     } while (num > high || num < low);  
  24. 24     return num;  
  25. 25 }  
wang@wang:~/test$ ./give_me_a_number 
Please enter a number (1 - 5): 3
Thanks for entering: 3
Please enter a number (5 - 10): 6
Thanks for entering: 6
(056) 重载函数

[cpp] view plain copy
  1.  1 // Triple  
  2.  2 // Demonstrates function overloading  
  3.  3 #include <iostream>  
  4.  4 #include <string>  
  5.  5 using namespace std;  
  6.  6 int triple(int number);  
  7.  7 string triple(string text);  
  8.  8   
  9.  9 int main()  
  10. 10 {  
  11. 11     cout << "Tripling 5: " << triple(5) << "\n";  
  12. 12     cout << "Tripling 'gamer': " << triple("gamer") << "\n";  
  13. 13     return 0;  
  14. 14 }  
  15. 15   
  16. 16 int triple(int number) {  
  17. 17     return (number * 3);  
  18. 18 }  
  19. 19   
  20. 20 string triple(string text) {  
  21. 21     return (text + text + text);  
  22. 22 }  
wang@wang:~/test$ ./triple 
Tripling 5: 15
Tripling 'gamer': gamergamergamer
(057) 内联函数

内联函数和默认参数相反,默认参数是在生命中,内联函数是在定义中。

[cpp] view plain copy
  1.  1 // Taking Damage  
  2.  2 // Demonstrates function inlining  
  3.  3 #include <iostream>  
  4.  4 int radiation(int health);  
  5.  5 using namespace std;  
  6.  6   
  7.  7 int main()  
  8.  8 {  
  9.  9     int health = 80;  
  10. 10     cout << "Your health is " << health << "\n";  
  11. 11     health = radiation(health);  
  12. 12     cout << "After radiation exposure your health is " << health << endl;  
  13. 13     health = radiation(health);  
  14. 14     cout << "After radiation exposure your health is " << health << endl;  
  15. 15     health = radiation(health);  
  16. 16     cout << "After radiation exposure your health is " << health << endl;  
  17. 17     return 0;  
  18. 18 }  
  19. 19   
  20. 20 inline int radiation(int health) {  
  21. 21     return (health / 2);  
  22. 22 }                    

wang@wang:~/test$ ./taking_damage 
Your health is 80
After radiation exposure your health is 40
After radiation exposure your health is 20
After radiation exposure your health is 10
(058) 综合举例

[cpp] view plain copy
  1. // Mad-Lib  
  2. // Creates a story based on user input  
  3. #include <iostream>  
  4. #include <string>  
  5. using namespace std;  
  6. string askText(string prompt);  
  7. int askNumber(string prompt);  
  8. void tellStory(string name, string noun, int number, string bodyPart, string verb);  
  9.   
  10. int main()  
  11. {  
  12.     cout << "Welcome to Mad Lib.\n";  
  13.     cout << "Answer the following questions to help create a new story.\n";  
  14.     string name = askText("Please enter a name: ");  
  15.     string noun = askText("Please enter a plural noun: ");  
  16.     int number = askNumber("Please enter a number: ");  
  17.     string bodyPart = askText("Please enter a body part: ");  
  18.     string verb = askText("Please enter a verb: ");  
  19.     tellStory(name, noun, number, bodyPart, verb);  
  20.     return 0;  
  21. }  
  22.   
  23. string askText(string prompt)  
  24. {  
  25.     string text;  
  26.     cout << prompt;  
  27.     cin >> text;  
  28.     return text;  
  29. }  
  30.   
  31. int askNumber(string prompt)  
  32. {  
  33.     int num;  
  34.     cout << prompt;  
  35.     cin >> num;  
  36.     return num;  
  37. }  
  38.   
  39. void tellStory(string name, string noun, int number, string bodyPart, string verb)  
  40. {  
  41.     cout << "Here's your story:\n";  
  42.     cout << "The famous explorer " << name;  
  43.     cout << " had nearly given up a life-long quest to find.\n";  
  44.     cout << "The Lost City of " << noun << " when one day, the " << noun;  
  45.     cout << " found the explorer.\n";  
  46.     cout << "Surrounded by " << number << " " << noun;  
  47.     cout << ", a tear came to " << name << "'s " << bodyPart << ".\n";  
  48.     cout << "After all this time, the quest was finally over. ";  
  49.     cout << "And then, then " << noun << endl;  
  50.     cout << "promptly devoured ";  
  51.     cout << name << ". ";  
  52.     cout << "The moral of the story? Be careful what you " << verb << " for.\n";  
  53. }  
wang@wang:~/test$ ./mad_lib 
Welcome to Mad Lib.
Answer the following questions to help create a new story.
Please enter a name: wang
Please enter a plural noun: wang
Please enter a number: 4
Please enter a body part: head
Please enter a verb: do
Here's your story:
The famous explorer wang had nearly given up a life-long quest to find.
The Lost City of wang when one day, the wang found the explorer.
Surrounded by 4 wang, a tear came to wang's head.
After all this time, the quest was finally over. And then, then wang
promptly devoured wang. The moral of the story? Be careful what you dofor.
(059) 习题

1. 默认参数放在函数生命最后。

2.  Two function, one for input, another for judge.

[cpp] view plain copy
  1. // Hangman  
  2. // The classic game of hangman  
  3. #include <iostream>  
  4. #include <string>  
  5. #include <vector>  
  6. #include <algorithm>  
  7. #include <ctime>  
  8. #include <cctype>  
  9.   
  10. using namespace std;  
  11.   
  12. char guesschar() {  
  13.     char guess;  
  14.     cout << "Enter your guess: ";  
  15.     cin >> guess;  
  16.     // make uppercase since secret word in uppercase  
  17.     guess = toupper(guess);  
  18.     return guess;  
  19. }  
  20.   
  21. bool include(char c, string word) {  
  22.     for (int i = 0; i < word.size(); ++i)  
  23.         if (c == word[i])  
  24.             return true;  
  25. }  
  26.   
  27. int main(int argc, char *argv[])  
  28. {  
  29.     // setup  
  30.     // maximum number of incorrect guesses allowed  
  31.     const int MAX_WRONG = 8;  
  32.     vector<string> words;  
  33.     words.push_back("GUESS");  
  34.     words.push_back("HANGMAN");  
  35.     words.push_back("DIFFICULT");  
  36.     srand(static_cast<unsigned int>(time(0)));  
  37.     random_shuffle(words.begin(), words.end());  
  38.     const string THE_WORD = words[0];  
  39.     // number of incorrect guesses  
  40.     int wrong = 0;  
  41.     // word guessed so far  
  42.     string soFar(THE_WORD.size(), '-');  
  43.     // letters already guessed  
  44.     string used = "";  
  45.   
  46.     cout << "Welcome to Hangman. Good luck!\n";  
  47.   
  48.     // main loop  
  49.     while ((wrong < MAX_WRONG) && (soFar != THE_WORD)) {  
  50.         cout << "You have " << (MAX_WRONG - wrong) << " incorrect guesses left.\n";  
  51.         cout << "You have used the following letters: " << used << endl;  
  52.         cout << "So far, the word is: " << soFar << endl;  
  53.         char guess = guesschar();  
  54.         while (used.find(guess) != string::npos) {  
  55.             cout << "You have already guessed " << guess << endl;  
  56.             guess = getchar();  
  57.         }  
  58.         used += guess;  
  59.         if (include(guess, THE_WORD)) {  
  60.             cout << "That's right! " << guess << " is in the word.\n";  
  61.             // update soFar to include newly guessed letter  
  62.             for (int i = 0; i < THE_WORD.size(); ++i)  
  63.                 if (THE_WORD[i] == guess)  
  64.                     soFar[i] = guess;  
  65.         } else {  
  66.             cout << "Sorry, " << guess << " isn't in the word.\n";  
  67.             ++wrong;  
  68.         }  
  69.     }  
  70.     // shut down  
  71.     if (wrong == MAX_WRONG)  
  72.         cout << "You have been hanged!\n";  
  73.     else  
  74.         cout << "You guess it!\n";  
  75.     cout << "The word was " << THE_WORD << endl;  
  76.   
  77.     return 0;  
  78. }  
Welcome to Hangman. Good luck!
You have 8 incorrect guesses left.
You have used the following letters: 
So far, the word is: -----
Enter your guess: E
That's right! E is in the word.
You have 8 incorrect guesses left.
You have used the following letters: E
So far, the word is: --E--
Enter your guess: F
Sorry, F isn't in the word.
You have 7 incorrect guesses left.
You have used the following letters: EF
So far, the word is: --E--
Enter your guess: D
Sorry, D isn't in the word.
You have 6 incorrect guesses left.
You have used the following letters: EFD
So far, the word is: --E--
Enter your guess: S
That's right! S is in the word.
You have 6 incorrect guesses left.
You have used the following letters: EFDS
So far, the word is: --ESS
Enter your guess: G
That's right! G is in the word.
You have 6 incorrect guesses left.
You have used the following letters: EFDSG
So far, the word is: G-ESS
Enter your guess: E
You have already guessed E
Sorry, 
 isn't in the word.
You have 5 incorrect guesses left.
You have used the following letters: EFDSG
So far, the word is: G-ESS
Enter your guess: U
That's right! U is in the word.
You guess it!
The word was GUESS

Press <RETURN> to close this window...

3. default argument

[cpp] view plain copy
  1.  1 #include <iostream>  
  2.  2 #include <string>  
  3.  3 using namespace std;  
  4.  4   
  5.  5 int getNumber(string str = "Get an int: ");  
  6.  6 int main()  
  7.  7 {  
  8.  8     int i = getNumber();  
  9.  9     int j = getNumber("Get an number: ");  
  10. 10     cout << i << " " << j << endl;  
  11. 11     return 0;  
  12. 12 }  
  13. 13   
  14. 14 int getNumber(string str) {  
  15. 15     cout << str;  
  16. 16     int n;  
  17. 17     cin >> n;  
  18. 18     return n;  
  19. 19 }  
wang@wang:~/test$ ./default_arg 
Get an int: 4
Get an number: 5
4 5


Chapter 6: References: Tic-Tac-Toe

(060) 引用,引用的简单举例

[cpp] view plain copy
  1.  1 // Referencing  
  2.  2 // Demonstrates using reference  
  3.  3 #include<iostream>  
  4.  4 using namespace std;  
  5.  5   
  6.  6 int main()  
  7.  7 {  
  8.  8     int myScore = 1000;  
  9.  9     // create a reference  
  10. 10     int &mikesScore = myScore;  
  11. 11     cout << "myScore is: " << myScore << endl;  
  12. 12     cout << "mikesScore is: " << mikesScore << endl;  
  13. 13     cout << "Adding 500 to myScore\n";  
  14. 14     myScore += 500;  
  15. 15     cout << "myScore is: " << myScore << endl;  
  16. 16     cout << "mikesScore is: " << mikesScore << endl;  
  17. 17     cout << "Adding 500 to mikesScore\n";  
  18. 18     mikesScore += 500;  
  19. 19     cout << "myScore is: " << myScore << endl;  
  20. 20     cout << "mikesScore is: " << mikesScore << endl;  
  21. 21     return 0;  
  22. 22 }  
wang@wang:~/test$ ./referencing 
myScore is: 1000
mikesScore is: 1000
Adding 500 to myScore
myScore is: 1500
mikesScore is: 1500
Adding 500 to mikesScore
myScore is: 2000
mikesScore is: 2000
(061) 通过引用修改原来变量举例

[cpp] view plain copy
  1.  1 // Swap  
  2.  2 // Demonstrates passing references to alter argument variables  
  3.  3 #include <iostream>  
  4.  4 using namespace std;  
  5.  5   
  6.  6 void badSwap(int x, int y);  
  7.  7 void goodSwap(int &x, int &y);  
  8.  8 int main()  
  9.  9 {  
  10. 10     int myScore = 150;  
  11. 11     int yourScore = 1000;  
  12. 12     cout << "Original values\n";  
  13. 13     cout << "myScore: " << myScore << endl;  
  14. 14     cout << "yourScore: " << yourScore << endl;  
  15. 15     cout << "Calling badSwap()\n";  
  16. 16     badSwap(myScore, yourScore);  
  17. 17     cout << "myScore: " << myScore << endl;  
  18. 18     cout << "yourScore: " << yourScore << endl;  
  19. 19     cout << "Calling goodSwap()\n";  
  20. 20     goodSwap(myScore, yourScore);  
  21. 21     cout << "myScore: " << myScore << endl;  
  22. 22     cout << "yourScore: " << yourScore << endl;  
  23. 23     return 0;  
  24. 24 }  
  25. 25   
  26. 26 void badSwap(int x, int y) {  
  27. 27     int temp = x;  
  28. 28     x = y;  
  29. 29     y = temp;  
  30. 30 }  
  31. 31   
  32. 32 void goodSwap(int &x, int &y) {  
  33. 33     int temp = x;  
  34. 34     x = y;  
  35. 35     y = temp;  
  36. 36 }  
wang@wang:~/test$ ./swap 
Original values
myScore: 150
yourScore: 1000
Calling badSwap()
myScore: 150
yourScore: 1000
Calling goodSwap()
myScore: 1000
yourScore: 150
(062) 利用引用可以减少拷贝

[cpp] view plain copy
  1.  1 // Inventory Displayer  
  2.  2 // Demonstrates constant references  
  3.  3 #include <iostream>  
  4.  4 #include <string>  
  5.  5 #include <vector>  
  6.  6 using namespace std;  
  7.  7 // parameter vec is a constant reference to a vector of strings  
  8.  8 void display(const vector<string> &inventory);  
  9.  9 int main()  
  10. 10 {  
  11. 11     vector<string> inventory;  
  12. 12     inventory.push_back("sword");  
  13. 13     inventory.push_back("armor");  
  14. 14     inventory.push_back("shield");  
  15. 15     display(inventory);  
  16. 16     return 0;  
  17. 17 }  
  18. 18   
  19. 19 // parameter vec is a constant reference to a vector of strings   
  20. 20 void display(const vector<string> &vec)  
  21. 21 {  
  22. 22     cout << "Your items:\n";  
  23. 23     for (vector<string>::const_iterator iter = vec.begin();  
  24. 24         iter != vec.end(); ++iter)  
  25. 25             cout << *iter << endl;  
  26. 26 }  
wang@wang:~/test$ ./inventory_displayer 
Your items:
sword
armor
shield
(063) 返回引用

[cpp] view plain copy
  1.  1 // Inventory Referencer  
  2.  2 // Demonstrates returning a reference  
  3.  3 #include <iostream>  
  4.  4 #include <string>  
  5.  5 #include <vector>  
  6.  6 using namespace std;  
  7.  7 // returns a reference to a string  
  8.  8 string & refToElement(vector<string> &inventory, int i);  
  9.  9 int main()  
  10. 10 {  
  11. 11     vector<string> inventory;  
  12. 12     inventory.push_back("sword");  
  13. 13     inventory.push_back("armor");  
  14. 14     inventory.push_back("shield");  
  15. 15     // displays string that the returned reference refers to  
  16. 16     cout << "Sending the returned reference to cout:\n";  
  17. 17     cout << refToElement(inventory, 0) << "\n";  
  18. 18     // assigns one reference to another  
  19. 19     cout << "Assigning the returned reference to another reference.\n";  
  20. 20     string &rStr = refToElement(inventory, 1);  
  21. 21     cout << "Send the new reference to cout:\n";  
  22. 22     cout << rStr << endl;  
  23. 23     // copies a string object  
  24. 24     cout << "Assigning the returned reference to a string object.\n";  
  25. 25     string str = refToElement(inventory, 2);  
  26. 26     cout << "Sending the new string object to cout:\n";  
  27. 27     cout << str << endl;  
  28. 28     // altering the string object through a returned reference  
  29. 29     cout << "Altering an object through a returned reference.\n";  
  30. 30     rStr = "Healing Potion";  
  31. 31     cout << "Sending the altered object to cout:\n";  
  32. 32     cout << inventory[1] << endl;  
  33. 33     return 0;  
  34. 34 }  
  35. 35 // returns a reference to a string  
  36. 36 string & refToElement(vector<string> &vec, int i)  
  37. 37 {  
  38. 38     return vec[i];  
  39. 39 }  
wang@wang:~/test$ ./inventory_referencer 
Sending the returned reference to cout:
sword
Assigning the returned reference to another reference.
Send the new reference to cout:
armor
Assigning the returned reference to a string object.
Sending the new string object to cout:
shield
Altering an object through a returned reference.
Sending the altered object to cout:
Healing Potion

(064) 这个例子有难度,自己编写没有成功,有点惭愧,贴出作者写的代码。

我觉得是一个初学者比较容易学会的游戏。

其中还涉及到计算机怎么走更合适。

第一,如果计算机下步能赢,就把棋子下在那一步;

第二,如果下步人类会赢,就把棋子下在人类那一步;

第三,根据棋盘剩余的最好的位置下子,第一个最好的位置是正中间。

[cpp] view plain copy
  1. // Tic-Tac-Toe  
  2. // Plays the game of tic-tac-toe against a human opponent  
  3.   
  4. #include <iostream>  
  5. #include <string>  
  6. #include <vector>  
  7. #include <algorithm>  
  8.   
  9. using namespace std;  
  10.   
  11. // global constants  
  12. const char X = 'X';  
  13. const char O = 'O';  
  14. const char EMPTY = ' ';  
  15. const char TIE = 'T';  
  16. const char NO_ONE = 'N';  
  17.   
  18. // function prototypes  
  19. // 相当于开始前的说明,比如怎么下棋,选择0 - 8个数  
  20. void instructions();  
  21. // 根据问题,回答y 或者 n  
  22. char askYesNo(string question);  
  23. // 根绝high low和question选择输入一个数  
  24. int askNumber(string question, int high, int low = 0);  
  25. // 人类选择是否先下棋,先下的为X  
  26. char humanPiece();  
  27. // 交换对手  
  28. char opponent(char piece);  
  29. // 显示棋局  
  30. void displayBoard(const vector<char>& board);  
  31. // 判断哪个是胜利者  
  32. char winner(const vector<char>& board);  
  33. // 判断这步棋是否有效  
  34. bool isLegal(const vector<char>& board, int move);  
  35. // 人类下棋  
  36. int humanMove(const vector<char>& board, char human);  
  37. // 电脑下棋  
  38. int computerMove(vector<char> board, char computer);  
  39. // 宣布获胜者  
  40. void announceWinner(char winner, char computer, char human);  
  41.   
  42. // main function  
  43. int main()  
  44. {  
  45.     int move;  
  46.     const int NUM_SQUARES = 9;  
  47.     vector<char> board(NUM_SQUARES, EMPTY);  
  48.   
  49.     instructions();  
  50.     char human = humanPiece();  
  51.     char computer = opponent(human);  
  52.     char turn = X;  
  53.     displayBoard(board);  
  54.   
  55.     while (winner(board) == NO_ONE)  
  56.     {  
  57.         if (turn == human)  
  58.         {  
  59.             move = humanMove(board, human);  
  60.             board[move] = human;  
  61.         }  
  62.         else  
  63.         {  
  64.             move = computerMove(board, computer);  
  65.             board[move] = computer;  
  66.         }  
  67.         displayBoard(board);  
  68.         turn = opponent(turn);  
  69.     }  
  70.   
  71.     announceWinner(winner(board), computer, human);  
  72.   
  73.     return 0;  
  74. }  
  75.   
  76. // functions  
  77. void instructions()  
  78. {  
  79.     cout << "Welcome to the ultimate man-machine showdown: Tic-Tac-Toe.\n";  
  80.     cout << "--where human brain is pit against silicon processor\n\n";  
  81.   
  82.     cout << "Make your move known by entering a number, 0 - 8.  The number\n";  
  83.     cout << "corresponds to the desired board position, as illustrated:\n\n";  
  84.       
  85.     cout << "       0 | 1 | 2\n";  
  86.     cout << "       ---------\n";  
  87.     cout << "       3 | 4 | 5\n";  
  88.     cout << "       ---------\n";  
  89.     cout << "       6 | 7 | 8\n\n";  
  90.   
  91.     cout << "Prepare yourself, human.  The battle is about to begin.\n\n";  
  92. }  
  93.   
  94. char askYesNo(string question)  
  95. {  
  96.     char response;  
  97.     do  
  98.     {  
  99.         cout << question << " (y/n): ";  
  100.         cin >> response;  
  101.     } while (response != 'y' && response != 'n');  
  102.   
  103.     return response;  
  104. }  
  105.   
  106. int askNumber(string question, int high, int low)  
  107. {  
  108.     int number;  
  109.     do  
  110.     {  
  111.         cout << question << " (" << low << " - " << high << "): ";  
  112.         cin >> number;  
  113.     } while (number > high || number < low);  
  114.   
  115.     return number;  
  116. }  
  117.   
  118. char humanPiece()  
  119. {  
  120.     char go_first = askYesNo("Do you require the first move?");  
  121.     if (go_first == 'y')  
  122.     {  
  123.         cout << "\nThen take the first move.  You will need it.\n";  
  124.         return X;  
  125.     }  
  126.     else  
  127.     {  
  128.         cout << "\nYour bravery will be your undoing... I will go first.\n";  
  129.         return O;  
  130.     }  
  131. }  
  132.   
  133. char opponent(char piece)  
  134. {  
  135.     if (piece == X)  
  136.     {  
  137.         return O;  
  138.     }  
  139.     else  
  140.     {  
  141.         return X;  
  142.     }  
  143. }  
  144.   
  145. void displayBoard(const vector<char>& board)  
  146. {  
  147.     cout << "\n\t" << board[0] << " | " << board[1] << " | " << board[2];  
  148.     cout << "\n\t" << "---------";  
  149.     cout << "\n\t" << board[3] << " | " << board[4] << " | " << board[5];  
  150.     cout << "\n\t" << "---------";  
  151.     cout << "\n\t" << board[6] << " | " << board[7] << " | " << board[8];  
  152.     cout << "\n\n";  
  153. }  
  154.   
  155. char winner(const vector<char>& board)  
  156. {  
  157.     // all possible winning rows  
  158.     const int WINNING_ROWS[8][3] = { {0, 1, 2},  
  159.                                      {3, 4, 5},  
  160.                                      {6, 7, 8},  
  161.                                      {0, 3, 6},  
  162.                                      {1, 4, 7},  
  163.                                      {2, 5, 8},  
  164.                                      {0, 4, 8},  
  165.                                      {2, 4, 6} };  
  166.     const int TOTAL_ROWS = 8;  
  167.   
  168.     // if any winning row has three values that are the same (and not EMPTY),  
  169.     // then we have a winner  
  170.     for(int row = 0; row < TOTAL_ROWS; ++row)  
  171.     {  
  172.         if ( (board[WINNING_ROWS[row][0]] != EMPTY) &&  
  173.              (board[WINNING_ROWS[row][0]] == board[WINNING_ROWS[row][1]]) &&  
  174.              (board[WINNING_ROWS[row][1]] == board[WINNING_ROWS[row][2]]) )  
  175.         {  
  176.             return board[WINNING_ROWS[row][0]];  
  177.         }  
  178.     }  
  179.   
  180.     // since nobody has won, check for a tie (no empty squares left)  
  181.     if (count(board.begin(), board.end(), EMPTY) == 0)  
  182.         return TIE;  
  183.   
  184.     // since nobody has won and it isn't a tie, the game ain't over  
  185.     return NO_ONE;  
  186. }  
  187.   
  188. inline bool isLegal(int move, const vector<char>& board)  
  189. {  
  190.     return (board[move] == EMPTY);  
  191. }  
  192.   
  193. int humanMove(const vector<char>& board, char human)  
  194. {  
  195.     int move = askNumber("Where will you move?", (board.size() - 1));  
  196.     while (!isLegal(move, board))  
  197.     {  
  198.         cout << "\nThat square is already occupied, foolish human.\n";  
  199.         move = askNumber("Where will you move?", (board.size() - 1));  
  200.     }  
  201.     cout << "Fine...\n";  
  202.   
  203.     return move;  
  204. }  
  205.   
  206. int computerMove(vector<char> board, char computer)  
  207. {   
  208.     unsigned int move = 0;  
  209.     bool found = false;  
  210.   
  211.     //if computer can win on next move, that’s the move to make  
  212.     while (!found && move < board.size())  
  213.     {  
  214.         if (isLegal(move, board))  
  215.         {  
  216. //try move  
  217.             board[move] = computer;  
  218.             //test for winner  
  219.             found = winner(board) == computer;     
  220.             //undo move  
  221.             board[move] = EMPTY;  
  222.         }  
  223.   
  224.         if (!found)  
  225.         {  
  226.             ++move;  
  227.         }  
  228.     }  
  229.     
  230.     //otherwise, if opponent can win on next move, that's the move to make  
  231.     if (!found)  
  232.     {  
  233.         move = 0;  
  234.         char human = opponent(computer);  
  235.   
  236.         while (!found && move < board.size())  
  237.         {  
  238.             if (isLegal(move, board))  
  239.             {  
  240.          //try move  
  241.          board[move] = human;    
  242.         //test for winner  
  243.                 found = winner(board) == human;       
  244.                 //undo move  
  245.                 board[move] = EMPTY;          
  246.             }  
  247.   
  248.             if (!found)  
  249.             {  
  250.                 ++move;  
  251.             }  
  252.         }  
  253.     }  
  254.   
  255.     //otherwise, moving to the best open square is the move to make  
  256.     if (!found)  
  257.     {  
  258.         move = 0;  
  259.         unsigned int i = 0;  
  260.   
  261.         const int BEST_MOVES[] = {4, 0, 2, 6, 8, 1, 3, 5, 7};  
  262.         //pick best open square  
  263.         while (!found && i <  board.size())  
  264.         {  
  265.             move = BEST_MOVES[i];  
  266.             if (isLegal(move, board))  
  267.             {  
  268.                 found = true;  
  269.             }  
  270.   
  271.             ++i;  
  272.         }  
  273.     }  
  274.   
  275.     cout << "I shall take square number " << move << endl;  
  276.     return move;  
  277. }  
  278.   
  279. void announceWinner(char winner, char computer, char human)  
  280. {  
  281.     if (winner == computer)  
  282.     {  
  283.         cout << winner << "'s won!\n";  
  284.         cout << "As I predicted, human, I am triumphant once more -- proof\n";  
  285.         cout << "that computers are superior to humans in all regards.\n";  
  286.     }  
  287.   
  288.     else if (winner == human)  
  289.     {  
  290.         cout << winner << "'s won!\n";  
  291.         cout << "No, no!  It cannot be!  Somehow you tricked me, human.\n";  
  292.         cout << "But never again!  I, the computer, so swear it!\n";  
  293.     }  
  294.   
  295.     else  
  296.     {  
  297.         cout << "It's a tie.\n";  
  298.         cout << "You were most lucky, human, and somehow managed to tie me.\n";  
  299.         cout << "Celebrate... for this is the best you will ever achieve.\n";  
  300.     }  
  301. }  
这个游戏还是需要逻辑的,建议多写这样的游戏锻炼思维。

(065) 习题

1. void tellStory(string &name, string &noun, int &number, string &bodyPart, string &verb);

2. invalid initialization of reference of type ‘float&’ from expression of type ‘int’

3. 传递临时变量,导致引用无效。


Chapter 7: Pointers: Tic-Tac-Toe 2.0

(066)指针简单举例

[cpp] view plain copy
  1.  1 // Pointing  
  2.  2 // Demonstrates using pointers  
  3.  3 #include <iostream>  
  4.  4 #include <string>  
  5.  5 using namespace std;  
  6.  6   
  7.  7 int main()  
  8.  8 {  
  9.  9     int *pScore = 0;  
  10. 10     int score = 1000;  
  11. 11     // assign pointer pScore address of variable score  
  12. 12     pScore = &score;  
  13. 13     cout << "Assigning &score to pScore\n";  
  14. 14     cout << "&score is: " << &score << "\n";  
  15. 15     cout << "pScore is: " << pScore << endl;  
  16. 16     cout << "score is: " << score << endl;  
  17. 17     cout << "*pScore is: " << pScore << endl;  
  18. 18     cout << "Adding 500 to score\n";  
  19. 19     score += 500;  
  20. 20     cout << "score is: " << score << endl;  
  21. 21     cout << "*pScore is: " << *pScore << endl;  
  22. 22     cout << "Adding 500 to *pScore\n";  
  23. 23     *pScore += 500;  
  24. 24     cout << "score is: " << score << endl;  
  25. 25     cout << "*pScore is: " << *pScore << endl;  
  26. 26     cout << "Assigning &newScore to pScore" << endl;  
  27. 27     int newScore = 5000;  
  28. 28     pScore = &newScore;  
  29. 29     cout << "&newScore is: " << &newScore << endl;  
  30. 30     cout << "pScore is: " << pScore << endl;  
  31. 31     cout << "newScore is; " << newScore << endl;  
  32. 32     cout << "pScore is: " << *pScore << endl;  
  33. 33     cout << "Assigning &str to pStr" << endl;  
  34. 34     string str = "score";  
  35. 35     string *pStr = &str;  
  36. 36     cout << "str is: " << str << endl;  
  37. 37     cout << "*pStr is: " << *pStr << endl;  
  38. 38     cout << "(*pStr).size() is: " << (*pStr).size() << endl;  
  39. 39     cout << "pStr->size() is: " << pStr->size() << endl;  
  40. 40     return 0;  
  41. 41 }  
wang@wang:~/test$ ./pointing 
Assigning &score to pScore
&score is: 0x7ffffba2df58
pScore is: 0x7ffffba2df58
score is: 1000
*pScore is: 0x7ffffba2df58
Adding 500 to score
score is: 1500
*pScore is: 1500
Adding 500 to *pScore
score is: 2000
*pScore is: 2000
Assigning &newScore to pScore
&newScore is: 0x7ffffba2df5c
pScore is: 0x7ffffba2df5c
newScore is; 5000
pScore is: 5000
Assigning &str to pStr
str is: score
*pStr is: score
(*pStr).size() is: 5
pStr->size() is: 5
(067) const pointer

int score = 100;

// illegal -- you must initialze a constant

int *const pScore = &score;

// illegal -- pScore can't point to a

pScore = &anotherScore;

(068) pointer to a constant

// a pointer to a constant

const int *pNumber;

int lives = 3;

pNumber = &lives;

// illegal -- can't use pointer to a constant to change

*pNumber -= 1;

(069) 传递参数举例

[cpp] view plain copy
  1.  1 // Swap Pointer  
  2.  2 // Demonstrates passing constant pointers to alter argument variables  
  3.  3 #include <iostream>  
  4.  4 using namespace std;  
  5.  5 void badSwap(int x, int y);  
  6.  6 void goodSwap(int *const pX, int *const pY);  
  7.  7 int main()  
  8.  8 {  
  9.  9     int myScore = 150;  
  10. 10     int yourScore = 1000;  
  11. 11     cout << "Original values\n";  
  12. 12     cout << "myScore: " << myScore << endl;  
  13. 13     cout << "yourScore: " << yourScore << endl;  
  14. 14     cout << "Calling basSwap()\n";  
  15. 15     badSwap(myScore, yourScore);  
  16. 16     cout << "myScore: " << myScore << endl;  
  17. 17     cout << "yourScore: " << yourScore << endl;  
  18. 18     goodSwap(&myScore, &yourScore);  
  19. 19     cout << "myScore: " << myScore << endl;  
  20. 20     cout << "yourScore: " << yourScore << endl;  
  21. 21     return 0;  
  22. 22 }  
  23. 23   
  24. 24 void badSwap(int x, int y) {  
  25. 25     int temp;  
  26. 26     temp = x;  
  27. 27     x = y;  
  28. 28     y = temp;  
  29. 29 }  
  30. 30   
  31. 31 void goodSwap(int *const pX, int *const pY) {  
  32. 32     int temp;  
  33. 33     temp = *pX;  
  34. 34     *pX = *pY;  
  35. 35     *pY = temp;  
  36. 36 }  
wang@wang:~/test$ ./swap_pointer_ver 
Original values
myScore: 150
yourScore: 1000
Calling basSwap()
myScore: 150
yourScore: 1000
myScore: 1000
yourScore: 150
(070) 返回指针

[cpp] view plain copy
  1.  1 // Inventory Pointer  
  2.  2 // Demonstrates returning a pointer  
  3.  3 #include <iostream>  
  4.  4 #include <string>  
  5.  5 #include <vector>  
  6.  6 using namespace std;  
  7.  7 // returns a pointer to a string element  
  8.  8 string *ptrToElement(vector<string> *const pVec, int i);  
  9.  9   
  10. 10 int main()  
  11. 11 {  
  12. 12     vector<string> inventory;  
  13. 13     inventory.push_back("sword");  
  14. 14     inventory.push_back("armor");  
  15. 15     inventory.push_back("shield");  
  16. 16     // displays string object that the returned pointer points to  
  17. 17     cout << "Sending the object pointed to by returned pointer to cout:\n";  
  18. 18     cout << *(ptrToElement(&inventory, 0)) << endl;  
  19. 19     cout << "Assigning the returned pointer to another pointer.\n";  
  20. 20     string *pStr = ptrToElement(&inventory, 1);  
  21. 21     cout << "Sending the object pointed to by new pointer to cout: \n";  
  22. 22     cout << *pStr << endl;  
  23. 23     cout << "Assigning object pointed to by pointer to a string object.\n";  
  24. 24     string str = *(ptrToElement(&inventory, 2));  
  25. 25     cout << "Sending the new string object to cout:\n";  
  26. 26     cout << str << endl;  
  27. 27     cout << "Altering an object through a returned pointer.\n";  
  28. 28     *pStr = "Healing potion";  
  29. 29     cout << "Sending the altered object to cout:\n";  
  30. 30     cout << inventory[1] << endl;  
  31. 31     return 0;  
  32. 32 }  
  33. 33 string *ptrToElement(vector<string> *const pVec, int i) {  
  34. 34     // return address of the string in position i of vector that pVec points to  
  35. 35     return &((*pVec)[i]);  
  36. 36 }  
wang@wang:~/test$ ./inventory_pointer 
Sending the object pointed to by returned pointer to cout:
sword
Assigning the returned pointer to another pointer.
Sending the object pointed to by new pointer to cout: 
armor
Assigning object pointed to by pointer to a string object.
Sending the new string object to cout:
shield
Altering an object through a returned pointer.
Sending the altered object to cout:
Healing potion

(071) 指针和数组的关系

[cpp] view plain copy
  1.  1 // Array Passer  
  2.  2 // Demonstrates relationship between pointers and arrays  
  3.  3 #include <iostream>  
  4.  4 using namespace std;  
  5.  5 void increase(int *const array, const int NUM_ELEMENTS);  
  6.  6 void display(const int *const array, const int NUM_ELEMENTS);  
  7.  7   
  8.  8 int main()  
  9.  9 {  
  10. 10     cout << "Creating an array of high scores.\n";  
  11. 11     const int NUM_SCORES = 3;  
  12. 12     int highScores[NUM_SCORES] = {3000, 5000, 7000};  
  13. 13     cout << "Displaying scores using array name as a constant pointer.\n";  
  14. 14     cout << *highScores << endl;  
  15. 15     cout << *(highScores + 1) << endl;  
  16. 16     cout << *(highScores + 2) << endl;  
  17. 17   
  18. 18     cout << "Increasing scores by passing array as a constant pointer.\n";  
  19. 19     increase(highScores, NUM_SCORES);  
  20. 20     cout << "Displaying scores by passing array as a constant pointer to a constant.\n";  
  21. 21     display(highScores, NUM_SCORES);  
  22. 22     return 0;  
  23. 23 }  
  24. 24   
  25. 25 void increase(int *const array, const int NUM_ELEMENTS) {  
  26. 26     for (int i = 0; i < NUM_ELEMENTS; i++) {  
  27. 27         array[i] += 50;  
  28. 28     }  
  29. 29 }  
  30. 30   
  31. 31 void display(const int * const array, const int NUM_ELEMENTS) {  
  32. 32     for (int i = 0; i < NUM_ELEMENTS; ++i) {  
  33. 33         cout << array[i] << endl;  
  34. 34     }  
  35. 35 }  
wang@wang:~/test$ ./array_passer 
Creating an array of high scores.
Displaying scores using array name as a constant pointer.
3000
5000
7000
Increasing scores by passing array as a constant pointer.
Displaying scores by passing array as a constant pointer to a constant.
3050
5050
7050
(072) Programmers often prefix pointer variable names with the letter "p" to remind them that the variable is indeed a pointer.

(073) 习题

1. 用指针访问字符串

[cpp] view plain copy
  1.  1 #include <iostream>  
  2.  2 #include <string>  
  3.  3 using namespace std;  
  4.  4   
  5.  5 int main()  
  6.  6 {  
  7.  7     string str = "hello world";  
  8.  8     string *pStr = &str;  
  9.  9     cout << "size: " << (*pStr).size() << endl;  
  10. 10     return 0;  
  11. 11 }  
wang@wang:~/test$ ./pstr 
size: 11
2. 就是把全部引用换成字符串,

传入时记得加上&字符。

3. 三个地址是一样的,记得取地址,是去取变量的地址,实在是有点想不通啊。

[cpp] view plain copy
  1.  1 #include <iostream>  
  2.  2 using namespace std;  
  3.  3   
  4.  4 int main()  
  5.  5 {  
  6.  6     int a = 10;  
  7.  7     int &b = a;  
  8.  8     int *c = &b;  
  9.  9     cout << &a << endl;  
  10. 10     cout << &b << endl;  
  11. 11     cout << b << endl;  
  12. 12     cout << &(*c) << endl;  
  13. 13     return 0;  
  14. 14 }  
wang@wang:~/te./addr
0x7fff91aadb2c
0x7fff91aadb2c
10
0x7fff91aadb2c


Chapter 8: Classes: Critter Caretaker

(074)类的简单举例

[cpp] view plain copy
  1.  1 // Simple Critter  
  2.  2 // Demonstrates creating a new type  
  3.  3 #include <iostream>  
  4.  4 using namespace std;  
  5.  5   
  6.  6 class Critter {  
  7.  7 public:  
  8.  8     int mHunger;  
  9.  9     void greet();  
  10. 10 };  
  11. 11   
  12. 12 void Critter::greet() {  
  13. 13     cout << "Hi. I'm a critter. My hunger level is " << mHunger << ".\n";  
  14. 14 }  
  15. 15   
  16. 16 int main() {  
  17. 17     Critter crit1;  
  18. 18     Critter crit2;  
  19. 19     crit1.mHunger = 9;  
  20. 20     cout << "crit1's hunger level is " << crit1.mHunger << ".\n";  
  21. 21     crit2.mHunger = 3;  
  22. 22     cout << "crit2's hunger level is " << crit2.mHunger << ".\n";  
  23. 23     crit1.greet();  
  24. 24     crit2.greet();  
  25. 25     return 0;  
  26. 26 }  
wang@wang:~/test$ ./simple_critter 
crit1's hunger level is 9.
crit2's hunger level is 3.
Hi. I'm a critter. My hunger level is 9.
Hi. I'm a critter. My hunger level is 3.
(075) 增加函数构造器

[cpp] view plain copy
  1.  1 // Constructor critter  
  2.  2 // Demonstrates constructors  
  3.  3 #include <iostream>  
  4.  4 using namespace std;  
  5.  5 class Critter {  
  6.  6 public:  
  7.  7     int m_Hunger;  
  8.  8     Critter(int hunger = 0);  
  9.  9     void greet();  
  10. 10 };  
  11. 11 Critter::Critter(int hunger) {  
  12. 12     cout << "A new critter has been born!" << endl;  
  13. 13     m_Hunger = hunger;  
  14. 14 }  
  15. 15 void Critter::greet() {  
  16. 16     cout << "Hi. I'm a critter. My hunger level is " << m_Hunger << ".\n";  
  17. 17 }  
  18. 18   
  19. 19 int main()  
  20. 20 {  
  21. 21     Critter crit(7);  
  22. 22     crit.greet();  
  23. 23     return 0;  
  24. 24 }  
wang@wang:~/test$ ./constructor_critter 
A new critter has been born!

Hi. I'm a critter. My hunger level is 7.

(076)对象综合举例

[html] view plain copy
  1. // Critter Caretaker  
  2. // Simulates caring for a virtual pet  
  3.   
  4. #include <iostream>  
  5.   
  6. using namespace std;  
  7.   
  8. class Critter {  
  9. public:  
  10.     Critter(int hunger = 0, int boredom = 0);  
  11.     void talk();  
  12.     void eat(int food = 4);  
  13.     void play(int fun = 4);  
  14. private:  
  15.     int m_Hunger;  
  16.     int m_Boredom;  
  17.     int getMood() const;  
  18.     void passTime(int time = 1);  
  19. };  
  20.   
  21. int main(int argc, char *argv[])  
  22. {  
  23.     Critter crit;  
  24.     crit.talk();  
  25.     int choice;  
  26.     int a;  
  27.     do {  
  28.         cout << "Criitter Caretakeer\n";  
  29.         cout << "0 - Quit\n";  
  30.         cout << "1 - Listen to your critter\n";  
  31.         cout << "2 - Feed your critter\n";  
  32.         cout << "3 - Play with your critter\n";  
  33.         cout << "Choice: ";  
  34.         cin >> choice;  
  35.         switch (choice) {  
  36.         case 0:  
  37.             cout << "Good-bye.\n";  
  38.             break;  
  39.         case 1:  
  40.             crit.talk();  
  41.             break;  
  42.         case 2:  
  43.             crit.eat();  
  44.             break;  
  45.         case 3:  
  46.             crit.play();  
  47.             break;  
  48.         default:  
  49.             cout << "Sorry, but " << choice << " isn't a valid choice.\n";  
  50.         }  
  51.     } while (choice != 0);  
  52.     return 0;  
  53. }  
  54.   
  55. Critter::Critter(int hunger, int boredom) :  
  56.     m_Hunger(hunger),  
  57.     m_Boredom(boredom)  
  58. {  
  59. }  
  60.   
  61. void Critter::talk()  
  62. {  
  63.     cout << "I'm a critter and I feel ";  
  64.     int mood = getMood();  
  65.     if (mood > 15)  
  66.         cout << "mad.\n";  
  67.     else if (mood > 10)  
  68.         cout << "frustrated.\n";  
  69.     else if (mood > 5)  
  70.         cout << "okay.\n";  
  71.     else  
  72.         cout << "happy.\n";  
  73.     passTime();  
  74. }  
  75.   
  76. void Critter::eat(int food)  
  77. {  
  78.     cout << "Brruppp.\n";  
  79.     m_Hunger -food;  
  80.     if (m_Hunger < 0)  
  81.         m_Hunger = 0;  
  82.     passTime();  
  83. }  
  84.   
  85. void Critter::play(int fun)  
  86. {  
  87.     cout << "Wheee!\n";  
  88.     m_Boredom -fun;  
  89.     if (m_Boredom < 0)  
  90.         m_Boredom = 0;  
  91.     passTime();  
  92. }  
  93.   
  94. inline int Critter::getMood() const  
  95. {  
  96.     return (m_Hunger + m_Boredom);  
  97. }  
  98.   
  99. void Critter::passTime(int time)  
  100. {  
  101.     m_Hunger += time;  
  102.     m_Boredom += time;  
  103. }  
wang@wang:~/workspace/beginc++game$ ./critter 
I'm a critter and I feel happy.
Criitter Caretakeer
0 - Quit
1 - Listen to your critter
2 - Feed your critter
3 - Play with your critter
Choice: 1
I'm a critter and I feel happy.
Criitter Caretakeer
0 - Quit
1 - Listen to your critter
2 - Feed your critter
3 - Play with your critter
Choice: 2
Brruppp.
Criitter Caretakeer
0 - Quit
1 - Listen to your critter
2 - Feed your critter
3 - Play with your critter
Choice: 0
Good-bye.

(077)习题1

1. 展示对象的变量

[html] view plain copy
  1. inline void Critter::list() const  
  2. {  
  3.     cout << "Hunger: " << m_Hunger << endl;  
  4.     cout << "Boredom: " << m_Boredom << endl;  
  5. }  
2. 看不懂什么意思。

3.变量没有初始化。


Chapter 9: Advanced Classes And Dynamic Memory: Game Lobby

(078) 组合举例

[html] view plain copy
  1. // Critter Farm  
  2. // Demonstrates object containment  
  3. #include <iostream>  
  4. #include <string>  
  5. #include <vector>  
  6. using namespace std;  
  7.   
  8. class Critter {  
  9. public:  
  10.     Critter(const string &name = "");  
  11.     string getName() const;  
  12. private:  
  13.     string m_Name;  
  14. };  
  15.   
  16. class Farm {  
  17. public:  
  18.     Farm(int spaces = 1);  
  19.     void add(const Critter &aCritter);  
  20.     void rollCall() const;  
  21. private:  
  22.     vector<Critter> m_Critters;  
  23. };  
  24.   
  25. int main(int argc, char *argv[])  
  26. {  
  27.     Critter crit("Poochie");  
  28.     cout << "My critter's name is " << crit.getName() << endl;  
  29.     cout << "Creating critter farm.\n";  
  30.     Farm myFarm(3);  
  31.     cout << "Adding three critters to the farm.\n";  
  32.     myFarm.add(Critter("Moe"));  
  33.     myFarm.add(Critter("Larry"));  
  34.     myFarm.add(Critter("Curly"));  
  35.     cout << "Calling Roll...\n";  
  36.     myFarm.rollCall();  
  37.     return 0;  
  38. }  
  39.   
  40. Critter::Critter(const string &name) : m_Name(name)  
  41. {  
  42.   
  43. }  
  44.   
  45. inline string Critter::getName() const  
  46. {  
  47.     return m_Name;  
  48. }  
  49.   
  50. Farm::Farm(int spaces)  
  51. {  
  52.     m_Critters.reserve(spaces);  
  53. }  
  54.   
  55. void Farm::add(const Critter &aCritter)  
  56. {  
  57.     m_Critters.push_back(aCritter);  
  58. }  
  59.   
  60. void Farm::rollCall() const  
  61. {  
  62.     for (vector<Critter>::const_iterator iter = m_Critters.begin(); iter != m_Critters.end(); ++iter)  
  63.         cout <<iter->getName() << " here.\n";  
  64. }  

My critter's name is Poochie

Creating critter farm.

Adding three critters to the farm.

Calling Roll...

Moe here.

Larry here.

Curly here.

(079) 友元与重载函数
[html] view plain copy
  1. // Friend Critter  
  2. // Demonstrates friend functions and operator overloading  
  3. #include <iostream>  
  4. #include <string>  
  5. using namespace std;  
  6.   
  7. class Critter {  
  8.     // make following global functions friends of the Critter class  
  9.     friend void peek(const Critter &aCritter);  
  10.     friend ostream& operator <<(ostream &os, const Critter& aCritter);  
  11. public:  
  12.     Critter(const string &name = "");  
  13. private:  
  14.     string m_Name;  
  15. };  
  16. Critter::Critter(const string &name) : m_Name(name) {}  
  17. void peek(const Critter &aCritter);  
  18. ostream &operator <<(ostream & os, const Critter &aCritter);  
  19.   
  20. int main(int argc, char *argv[])  
  21. {  
  22.     Critter crit("Poochie");  
  23.     cout << "Calling peek() to access crit's private data member, m_Name: \n";  
  24.     peek(crit);  
  25.     cout << "Sending crit object to cout with the << operator:\n";  
  26.     cout << crit;  
  27.     return 0;  
  28. }  
  29. // global friend function that can access all of a Critter object's members  
  30. void peek(const Critter &aCritter)  
  31. {  
  32.     cout << aCritter.m_Name << endl;  
  33. }  
  34. // overloads the << operator so you can send a Critter object to cout  
  35. ostream &operator <<(ostream &os, const Critter &aCritter)  
  36. {  
  37.     os << "Critter Object - ";  
  38.     os << "m_Name: " << aCritter.m_Name;  
  39.     cout << endl;  
  40.     return os;  
  41. }  

Calling peek() to access crit's private data member, m_Name:

Poochie

Sending crit object to cout with the << operator:

Critter Object - m_Name: Poochie

(080) 动态内存分配

The new operator allocates memory on the heap and returns its address.

[html] view plain copy
  1. // Heap  
  2. // Demonstrates dynamically allocating memory  
  3.   
  4. #include <iostream>  
  5. using namespace std;  
  6. int* intOnHeap()  
  7. {  
  8.     int *pTemp = new int(20);  
  9.             return pTemp;  
  10. }  
  11. void leak1()  
  12. {  
  13.     int *drip1 = new int(30);  
  14. }  
  15. void leak2()  
  16. {  
  17.     int *drip2 = new int(50);  
  18.     drip2 = new int(100);  
  19.     delete drip2;  
  20. }  
  21.   
  22. int main(int argc, char *argv[])  
  23. {  
  24.     int *pHeap = new int;  
  25.     *pHeap = 10;  
  26.     cout << "*pHeap: " << *pHeap << "\n";  
  27.     int *pHeap2 = intOnHeap();  
  28.     cout << "*pHeap2: " << *pHeap2 << "\n";  
  29.     cout << "Freeing memory pointed to by pHeap.\n";  
  30.     delete pHeap;  
  31.     cout << "Freeig memory pointed to by pHeap2.\n";  
  32.     delete pHeap2;  
  33.     // get rid of danling pointers  
  34.     pHeap = 0;  
  35.     pHeap2 = 0;  
  36.     return 0;  
  37. }  

*pHeap: 10

*pHeap2: 20

Freeing memory pointed to by pHeap.

Freeig memory pointed to by pHeap2.

(081)带有指针的成员变量计算

[cpp] view plain copy
  1. // Heap Data Member  
  2. // Demonstrates an object with a dynamically allocated data member  
  3. #include <iostream>  
  4. #include <string>  
  5. using namespace std;  
  6.   
  7. class Critter {  
  8. public:  
  9.     Critter(const string& name = ""int age = 0);  
  10.     ~Critter();  
  11.     // copy constructor prototype  
  12.     Critter(const Critter &c);  
  13.     // overload assignment op  
  14.     Critter & operator=(const Critter& c);  
  15.     void greet() const;  
  16. private:  
  17.     string *m_pName;  
  18.     int m_Age;  
  19. };  
  20.   
  21. void testDestructor()  
  22. {  
  23.     Critter toDestory("Rover", 3);  
  24.     toDestory.greet();  
  25. }  
  26. void testCopyConstructor(Critter aCopy)  
  27. {  
  28.     aCopy.greet();  
  29. }  
  30. void testAssignmentOp()  
  31. {  
  32.     Critter crit1("crit1", 7);  
  33.     Critter crit2("crit2", 9);  
  34.     crit1 = crit2;  
  35.     crit1.greet();  
  36.     crit2.greet();  
  37.     Critter crit3("crit", 11);  
  38.     crit3 = crit3;  
  39.     crit3.greet();  
  40. }  
  41. int main(int argc, char *argv[])  
  42. {  
  43.     testDestructor();  
  44.     Critter crit("Poochie", 5);  
  45.     crit.greet();  
  46.     testCopyConstructor(crit);  
  47.     crit.greet();  
  48.     testAssignmentOp();  
  49.     return 0;  
  50. }  
  51.   
  52. Critter::Critter(const string &name, int age)  
  53. {  
  54.     cout << "Constructor called\n";  
  55.     m_pName = new string(name);  
  56.     m_Age = age;  
  57. }  
  58.   
  59. Critter::~Critter()  
  60. {  
  61.     cout << "Destructor called\n";  
  62.     delete m_pName;  
  63. }  
  64.   
  65. Critter::Critter(const Critter &c)  
  66. {  
  67.     cout << "Copy Constructor called\n";  
  68.     m_pName = new string(*(c.m_pName));  
  69.     m_Age = c.m_Age;  
  70. }  
  71.   
  72. Critter &Critter::operator=(const Critter &c)  
  73. {  
  74.     cout << "Overload Assignment Operator called\n";  
  75.     if (this != &c) {  
  76.         delete m_pName;  
  77.         m_pName = new string(*(c.m_pName));  
  78.         m_Age = c.m_Age;  
  79.     }  
  80.     return *this;  
  81. }  
  82.   
  83. void Critter::greet() const  
  84. {  
  85.     cout << "I'm " << *m_pName << " and I'm " << m_Age << " years old. ";  
  86.     cout << "&m_pName: " << &m_pName << endl;  
  87. }  
Constructor called
I'm Rover and I'm 3 years old. &m_pName: 0x7ffc9676e280
Destructor called
Constructor called
I'm Poochie and I'm 5 years old. &m_pName: 0x7ffc9676e2d0
Copy Constructor called
I'm Poochie and I'm 5 years old. &m_pName: 0x7ffc9676e2e0
Destructor called
I'm Poochie and I'm 5 years old. &m_pName: 0x7ffc9676e2d0
Constructor called
Constructor called
Overload Assignment Operator called
I'm crit2 and I'm 9 years old. &m_pName: 0x7ffc9676e260
I'm crit2 and I'm 9 years old. &m_pName: 0x7ffc9676e270
Constructor called
Overload Assignment Operator called
I'm crit and I'm 11 years old. &m_pName: 0x7ffc9676e280
Destructor called
Destructor called
Destructor called
Destructor called
(082) 需要析构器自己析构分配的堆空间

When you have a class with data members that point to values on the heap, you should write your own destructor so you can free the memory on the heap associated with an object before the object disappears, avoiding a memory leak.

(083)拷贝函数

The default copy constructor simply copies the value of each data member to data members of the same name in the new object - a member-wise copy.

With only a default copy constructor, the automatic copying of the object would result in a new object that points to the same single string on the heap because the pointer of the new object would simply get a copy of the address stored in the pointer of the original object.

(084)拷贝构造器

Critter(const Critter &c);

(085)本章综合举例

[cpp] view plain copy
  1. // Game Lobby  
  2. // Simulates a game lobby where players wait  
  3. #include <iostream>  
  4. #include <string>  
  5. using namespace std;  
  6. class Player {  
  7. public:  
  8.     Player(const string &name = "");  
  9.     string getName() const;  
  10.     Player *getNext() const;  
  11.     void setNext(Player *next);  
  12. private:  
  13.     string m_Name;  
  14.     // Pointer to next player in list  
  15.     Player *m_pNext;  
  16. };  
  17.   
  18.   
  19.   
  20. Player::Player(const string &name) : m_Name(name), m_pNext(0)  
  21. {  
  22.   
  23. }  
  24.   
  25. string Player::getName() const  
  26. {  
  27.     return m_Name;  
  28. }  
  29.   
  30. Player *Player::getNext() const  
  31. {  
  32.     return m_pNext;  
  33. }  
  34.   
  35. void Player::setNext(Player *next)  
  36. {  
  37.     m_pNext = next;  
  38. }  
  39.   
  40. class Lobby {  
  41.     friend ostream &operator<<(ostream &os, const Lobby& aLobby);  
  42. public:  
  43.     Lobby();  
  44.     ~Lobby();  
  45.     void addPlayer();  
  46.     void removePlayer();  
  47.     void clear();  
  48. private:  
  49.     // A pointer that points to a Player object, which represents the first person in line.  
  50.     Player *m_pHead;  
  51. };  
  52.   
  53. ostream &operator<<(ostream &os, const Lobby &aLobby)  
  54. {  
  55.     Player *pIter = aLobby.m_pHead;  
  56.     os << "\nHere's who's in the game lobby:\n";  
  57.     if (pIter == 0)  
  58.         os << "The lobby is empty.\n";  
  59.     else {  
  60.         while (pIter != 0) {  
  61.             os << pIter->getName() << endl;  
  62.             pIter = pIter->getNext();  
  63.         }  
  64.     }  
  65.     return os;  
  66. }  
  67.   
  68. Lobby::Lobby() : m_pHead(0)  
  69. {  
  70.   
  71. }  
  72.   
  73. Lobby::~Lobby()  
  74. {  
  75.     clear();  
  76. }  
  77.   
  78. void Lobby::addPlayer()  
  79. {  
  80.     // create a new player node  
  81.     cout << "Please enter the name of the new player: ";  
  82.     string name;  
  83.     cin >> name;  
  84.     Player *pNewPlayer = new Player(name);  
  85.     // if list is empty, make head of list this new player  
  86.     if (m_pHead == 0)  
  87.         m_pHead = pNewPlayer;  
  88.     // otherwise find the end of the list and add the player  
  89.     else {  
  90.         Player *pIter = m_pHead;  
  91.         while(pIter->getNext() != 0)  
  92.             pIter = pIter->getNext();  
  93.         pIter->setNext(pNewPlayer);  
  94.     }  
  95. }  
  96.   
  97. void Lobby::removePlayer()  
  98. {  
  99.     if (m_pHead == 0)  
  100.         cout << "The game lobby is empty. No one to remove!\n";  
  101.     else {  
  102.         Player *pTemp = m_pHead;  
  103.         m_pHead = m_pHead->getNext();  
  104.         delete pTemp;  
  105.     }  
  106. }  
  107.   
  108. void Lobby::clear()  
  109. {  
  110.     while (m_pHead != 0)  
  111.         removePlayer();  
  112. }  
  113.   
  114. int main(int argc, char *argv[])  
  115. {  
  116.     Lobby myLobby;  
  117.     int choice;  
  118.     do {  
  119.         cout << "\nGAME LOBBY\n";  
  120.         cout << "0 - Exit the program.\n";  
  121.         cout << "1 - Add a player to the lobby.\n";  
  122.         cout << "2 - Remove a player from the lobby.\n";  
  123.         cout << "3 - Clear the lobby.\n";  
  124.         cout << "Enter choice: ";  
  125.         cin >> choice;  
  126.         switch(choice) {  
  127.             case 0: cout << "Good-bye.\n"break;  
  128.             case 1: myLobby.addPlayer(); break;  
  129.             case 2: myLobby.removePlayer(); break;  
  130.             case 3: myLobby.clear(); break;  
  131.             default:  
  132.                 cout << "That was not a valid choice.\n";  
  133.         }  
  134.     } while (choice != 0);  
  135.   
  136.     return 0;  
  137. }  
GAME LOBBY
0 - Exit the program.
1 - Add a player to the lobby.
2 - Remove a player from the lobby.
3 - Clear the lobby.
Enter choice: 1
Please enter the name of the new player: wang

GAME LOBBY
0 - Exit the program.
1 - Add a player to the lobby.
2 - Remove a player from the lobby.
3 - Clear the lobby.
Enter choice: 2

GAME LOBBY
0 - Exit the program.
1 - Add a player to the lobby.
2 - Remove a player from the lobby.
3 - Clear the lobby.
Enter choice: 0
Good-bye.
(086) 习题

1. 增加一个<<重载

[cpp] view plain copy
  1. ostream &operator<<(ostream &os, const Player &aPlayer)  
  2. {  
  3.     os << aPlayer.getName();  
  4. }  
2. 改的都是错。

3. 内存泄露。


Chapter 10: Inheritance And Polymorphism: BlackJack

(087) Inheritance is especially useful when you want to create a more specialized version of an existing class because you can add data members and member functions to the new class to extend it.

(088) 简单的继承举例

[cpp] view plain copy
  1. // simple boss  
  2. // Demonstrates inheritance  
  3. #include <iostream>  
  4.   
  5. using namespace std;  
  6.   
  7. class Enemy {  
  8. public:  
  9.     int m_Damage;  
  10.     Enemy();  
  11.     void attack() const;  
  12. };  
  13.   
  14.   
  15.   
  16. Enemy::Enemy() : m_Damage(10)  
  17. {  
  18.   
  19. }  
  20.   
  21. void Enemy::attack() const  
  22. {  
  23.     cout << "Attack inflicts " << m_Damage << " damage points!\n";  
  24. }  
  25.   
  26. class Boss : public Enemy {  
  27. public:  
  28.     int m_DamageMultiplier;  
  29.     Boss();  
  30.     void specialAttack() const;  
  31. };  
  32.   
  33. Boss::Boss() : m_DamageMultiplier(3)  
  34. {  
  35.   
  36. }  
  37.   
  38. void Boss::specialAttack() const  
  39. {  
  40.     cout << "Special Attack inflicts " << (m_DamageMultiplier * m_Damage) << " damage points!\n";  
  41. }  
  42.   
  43. int main(int argc, char *argv[])  
  44. {  
  45.     cout << "Creating an enemy.\n";  
  46.     Enemy enemy1;  
  47.     enemy1.attack();  
  48.     cout << "Creating a boss.\n";  
  49.     Boss boss1;  
  50.     boss1.attack();  
  51.     boss1.specialAttack();  
  52.     return 0;  
  53. }  
Creating an enemy.
Attack inflicts 10 damage points!
Creating a boss.
Attack inflicts 10 damage points!
Special Attack inflicts 30 damage points!
(089) 没有被子类集成的函数

Constructors

Copy constructors

Destructors

Overloaded assignment operators

(090)可以将上一个例子修改为父类的修饰符修改为protected。

protected members are accessible only in their own class and certain derived classes, depending upon the access level in inheritance.

(091)重写父类

[cpp] view plain copy
  1. // overriding boss  
  2. // Demonstrates calling and overriding base member functions  
  3. #include <iostream>  
  4. using namespace std;  
  5. class Enemy {  
  6. public:  
  7.     Enemy(int damage = 10);  
  8.     void virtual taunt() const;  
  9.     void virtual attack() const;  
  10. private:  
  11.     int m_Damage;  
  12. };  
  13. class Boss : public Enemy {  
  14. public:  
  15.     Boss(int damage = 30);  
  16.     void virtual taunt() const;  
  17.     void virtual attack() const;  
  18. };  
  19.   
  20. int main(int argc, char *argv[])  
  21. {  
  22.     cout << "Enemy object:\n";  
  23.     Enemy anEnemy;  
  24.     anEnemy.taunt();  
  25.     anEnemy.attack();  
  26.     cout << "Boss object:\n";  
  27.     Boss aBoss;  
  28.     aBoss.taunt();  
  29.     aBoss.attack();  
  30.     return 0;  
  31. }  
  32.   
  33. Enemy::Enemy(int damage) : m_Damage(damage)  
  34. {  
  35.   
  36. }  
  37.   
  38. void Enemy::taunt() const  
  39. {  
  40.     cout << "The enemy says he will fight you.\n";  
  41. }  
  42.   
  43. void Enemy::attack() const  
  44. {  
  45.     cout << "Attack! Inflicts " << m_Damage << " damage points.\n";  
  46. }  
  47.   
  48. Boss::Boss(int damage) : Enemy(damage)  
  49. {  
  50.   
  51. }  
  52.   
  53. void Boss::taunt() const  
  54. {  
  55.     cout << "The boss says he will end your pitiful existence.\n";  
  56. }  
  57.   
  58. void Boss::attack() const  
  59. {  
  60.     Enemy::attack();  
  61.     cout << "And laught heartily at you.\n";  
  62. }  
Enemy object:
The enemy says he will fight you.
Attack! Inflicts 10 damage points.
Boss object:
The boss says he will end your pitiful existence.
Attack! Inflicts 30 damage points.
And laught heartily at you.
(092) 调用父类构造器

To call a base class constructor from a derived class constructor, after the derived constructor's parameter list, type a colon followed by the name of the base class, followed by a set of parentheses containing whatever parameters the base class constructor you're calling needs.

(093) 多态举例

[cpp] view plain copy
  1. // polymorphic bad guy  
  2. // demonstrates calling member functions danamically  
  3. #include <iostream>  
  4. using namespace std;  
  5. class Enemy {  
  6. public:  
  7.     Enemy(int damage = 10);  
  8.     virtual ~Enemy();  
  9.     void virtual attack() const;  
  10. protected:  
  11.     int *m_pDamage;  
  12. };  
  13. class Boss : public Enemy {  
  14. public:  
  15.     Boss(int multiplier = 3);  
  16.     virtual ~Boss();  
  17.     void virtual attack() const;  
  18. protected:  
  19.     int *m_pMultiplier;  
  20. };  
  21.   
  22. int main(int argc, char *argv[])  
  23. {  
  24.     cout << "Calling attack() on boss object through pointer to enemy:\n";  
  25.     Enemy *pBadGuy = new Boss();  
  26.     pBadGuy->attack();  
  27.     cout << "Deleting pointer to Enemy:\n";  
  28.     delete pBadGuy;  
  29.     pBadGuy = 0;  
  30.     return 0;  
  31. }  
  32.   
  33. Enemy::Enemy(int damage)  
  34. {  
  35.     m_pDamage = new int(damage);  
  36. }  
  37.   
  38. Enemy::~Enemy()  
  39. {  
  40.     cout << "In enemy destructor, deleting m_pDamage.\n";  
  41.     delete m_pDamage;  
  42.     m_pDamage = 0;  
  43. }  
  44.   
  45. void Enemy::attack() const  
  46. {  
  47.     cout << "An enemy attacks and inflicts " << *m_pDamage << " damage points.\n";  
  48. }  
  49.   
  50. Boss::Boss(int multiplier)  
  51. {  
  52.     m_pMultiplier = new int(multiplier);  
  53. }  
  54.   
  55. Boss::~Boss()  
  56. {  
  57.     cout << "In boss destrcutor, deleting m_pMultiplier.\n";  
  58.     delete m_pMultiplier;  
  59.     m_pMultiplier = 0;  
  60. }  
  61.   
  62. void Boss::attack() const  
  63. {  
  64.     cout << "A boss attacks and inflicts " << (*m_pDamage) * (*m_pMultiplier) << " damage points.\n";  
  65. }  
Calling attack() on boss object through pointer to enemy:
A boss attacks and inflicts 30 damage points.
Deleting pointer to Enemy:
In boss destrcutor, deleting m_pMultiplier.
In enemy destructor, deleting m_pDamage.
(094)抽象类

[cpp] view plain copy
  1. // abstract creature  
  2. // Demonstrates abstract classes  
  3. #include <iostream>  
  4. using namespace std;  
  5. class Creature {  
  6. public:  
  7.     Creature(int health = 100);  
  8.     // pure virtual function  
  9.     virtual void greet() const = 0;  
  10.     virtual void displayHealth() const;  
  11. protected:  
  12.     int m_Health;  
  13. };  
  14. class Orc : public Creature {  
  15. public:  
  16.     Orc(int health = 120);  
  17.     virtual void greet() const;  
  18. };  
  19.   
  20. int main(int argc, char *argv[])  
  21. {  
  22.     Creature *pCreature = new Orc();  
  23.     pCreature->greet();  
  24.     pCreature->displayHealth();  
  25.     return 0;  
  26. }  
  27.   
  28. Creature::Creature(int health) : m_Health(health)  
  29. {  
  30.   
  31. }  
  32.   
  33. void Creature::displayHealth() const  
  34. {  
  35.     cout << "Health: " << m_Health << endl;  
  36. }  
  37.   
  38. Orc::Orc(int health) : Creature(health)  
  39. {  
  40.   
  41. }  
  42.   
  43. void Orc::greet() const  
  44. {  
  45.     cout << "The orc grunts hello.\n";  
  46. }  
The orc grunts hello.
Health: 120

096. 纯虚函数

A pure virtual function is one to which you don't need to give a definition.

You specify a pure virtual function by placing an equal sign and a zero at the end of the function header.

When a class contains at least one pure virtual function, it's an abstract class.

097. 这个21点游戏比较难编辑。

单独作一篇文章

(097)习题

1. 增加FinalBoss类

[cpp] view plain copy
  1. class FinalBoss : public Boss {  
  2. public:  
  3.     FinalBoss();  
  4.     void MegaAttack();  
  5. };  
2. 第二个不会。

这本书很基础,但是有两个例子不错。

总的来说是快速熟悉C++,并不是教具体的语法等知识点。

更多地来源于自己的编程总结。


转载来源:http://blog.csdn.net/wan_exe/article/details/61930540


原创粉丝点击