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.
- 1 // Game Over
- 2 // A first C++ program
- 3 #include <iostream>
- 4
- 5 int main()
- 6 {
- 7 std::cout << "Game Over!" << std::endl;
- 8 return 0;
- 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
- 1 // Game Over 2.0
- 2 // Demonstrates a using directive
- 3
- 4 #include <iostream>
- 5 using namespace std;
- 6
- 7 int main()
- 8 {
- 9 cout << "Game Over!" << endl;
- 10 return 0;
- 11 }
wang@wang:~/workspace/beginc++game$ ./game_over2 Game Over!(008) 使用using declaration- 1 // Game Over 3.0
- 2 // Demonstrates using declarations
- 3
- 4 #include <iostream>
- 5 using std::cout;
- 6 using std::endl;
- 7
- 8 int main()
- 9 {
- 10 cout << "Game Over!" << endl;
- 11 return 0;
- 12 }
wang@wang:~/workspace/beginc++game$ ./game_over3Game Over!(009) 加减乘除
- 1 // Expensive Calculator
- 2 // Demonstrates built-in arithmetic operators
- 3
- 4 #include <iostream>
- 5 using namespace std;
- 6
- 7 int main()
- 8 {
- 9 cout << "7 + 3 = " << 7 + 3 << endl;
- 10 cout << "7 - 3 = " << 7 - 3 << endl;
- 11 cout << "7 * 3 = " << 7 * 3 << endl;
- 12
- 13 cout << "7 / 3 = " << 7 / 3 << endl;
- 14 cout << "7.0 / 3.0 = " << 7.0 / 3.0 << endl;
- 15
- 16 cout << "7 % 3 = " << 7 % 3 << endl;
- 17
- 18 cout << "7 + 3 * 5 = " << 7 + 3 * 5 << endl;
- 19 cout << "(7 + 3) * 5 = " << (7 + 3) * 5 << endl;
- 20
- 21 return 0;
- 22 }
wang@wang:~/workspace/beginc++game$ ./expensive_calculator 7 + 3 = 107 - 3 = 47 * 3 = 217 / 3 = 27.0 / 3.0 = 2.333337 % 3 = 17 + 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) 状态值举例
- 1 // Game Stats
- 2 // Demonstrates declaring and initializing variables
- 3
- 4 #include <iostream>
- 5 using namespace std;
- 6
- 7 int main()
- 8 {
- 9 int score;
- 10 double distance;
- 11 char playAgain;
- 12 bool shieldsUp;
- 13
- 14 short lives, aliensKilled;
- 15
- 16 score = 0;
- 17 distance = 1200.76;
- 18 playAgain = 'y';
- 19 shieldsUp = true;
- 20 lives = 3;
- 21 aliensKilled = 10;
- 22 double engineTemp = 6572.89;
- 23
- 24 cout << "score: " << score << endl;
- 25 cout << "distance: " << distance << endl;
- 26 cout << "playAgain: " << playAgain << endl;
- 27 // skipping shieldsUp since you don't generally print Boolean values
- 28 cout << "lives: " << lives << endl;
- 29 cout << "aliensKilled: " << aliensKilled << endl;
- 30 cout << "engineTemp: " << engineTemp << endl;
- 31
- 32 int fuel;
- 33 cout << "How much fuel? ";
- 34 cin >> fuel;
- 35 cout << "fuel: " << fuel << endl;
- 36
- 37 typedef unsigned short int ushort;
- 38 ushort bonus = 10;
- 39 cout << "bonus: " << bonus << endl;
- 40
- 41 return 0;
- 42 }
wang@wang:~/workspace/beginc++game$ ./game_stats score: 0distance: 1200.76playAgain: ylives: 3aliensKilled: 10engineTemp: 6572.89How much fuel? 12fuel: 12bonus: 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) 变量运算举例
- 1
- 2
- 3
- 4 #include <iostream>
- 5 using namespace std;
- 6
- 7 int main()
- 8 {
- 9 unsigned int score = 5000;
- 10 cout << "score: " << score << endl;
- 11
- 12
- 13 score = score + 100;
- 14 cout << "score: " << score << endl;
- 15
- 16
- 17 score += 100;
- 18 cout << "score: " << score << endl;
- 19
- 20
- 21 int lives = 3;
- 22 ++lives;
- 23 cout << "lives: " << lives << endl;
- 24
- 25 lives = 3;
- 26 lives++;
- 27 cout << "lives: " << lives << endl;
- 28
- 29 lives = 3;
- 30 int bonus = ++lives * 10;
- 31 cout << "lives, bonus = " << lives << ", " << bonus << endl;
- 32
- 33 lives = 3;
- 34 bonus = lives++ * 10;
- 35 cout << "lives, bonus = " << lives << ", " << bonus << endl;
- 36
- 37
- 38 score = 4294967295;
- 39 cout << "socre: " << score << endl;
- 40 ++score;
- 41 cout << "score: " << score << endl;
- 42
- 43 return 0;
- 44 }
wang@wang:~/test$ ./game_stat2 score: 5000score: 5100score: 5200lives: 4lives: 4lives, bonus = 4, 40lives, bonus = 4, 30socre: 4294967295score: 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.
- 1
- 2
- 3
- 4 #include <iostream>
- 5 using namespace std;
- 6
- 7 int main()
- 8 {
- 9 const int ALIEN_POINTS = 150;
- 10 int aliensKilled = 10;
- 11 int score = aliensKilled * ALIEN_POINTS;
- 12 cout << "score: " << score << endl;
- 13 enum difficulty {NOVICE, EASY, NORMAL, HARD, UNBEATABLE};
- 14 difficulty myDifficulty = EASY;
- 15 enum shipCost {FIGHTER_COST = 25, BOMBER_COST, CRUISER_COST = 50};
- 16 shipCost myShipCost = BOMBER_COST;
- 17 cout << "To upgrade my ship to a Cruiser will cost "
- 18 << (CRUISER_COST - myShipCost) << " Resource Points.\n";
- 19 return 0;
- 20 }
wang@wang:~/test$ ./game_stats3 score: 1500To upgrade my ship to a Cruiser will cost 24 Resource Points.(019) 综合举例有趣的文字游戏
- 1
- 2
- 3
- 4 #include <iostream>
- 5 #include <string>
- 6
- 7 using namespace std;
- 8 int main()
- 9 {
- 10 const int GOLD_PIECES = 900;
- 11 int adventurers, killed, survivors;
- 12 string leader;
- 13
- 14
- 15 cout << "Welcome to Lost Fortune\n";
- 16 cout << "Please enter the following for your personalized adventure\n";
- 17 cout << "Enter a number: ";
- 18 cin >> adventurers;
- 19 cout << "Enter a number, smaller than the first: ";
- 20 cin >> killed;
- 21 survivors = adventurers - killed;
- 22 cout << "Enter your last name: ";
- 23 cin >> leader;
- 24
- 25 cout << "A brave group of " << adventurers << " set out on a quest ";
- 26 cout << "-- in search of the lost treasure of the Ancient Dwarves. ";
- 27 cout << "The group was led by that legendary rogue, " << leader << ".\n";
- 28 cout << "Along the way, a band of marauding ogres ambushed the party. ";
- 29 cout << "All fought bravely under the command of " << leader;
- 30 cout << ", and the ogres were defeated, but at a cost. ";
- 31 cout << "Of the adventurers, " << killed << " were vanquished, ";
- 32 cout << "leaving just " << survivors << " in the group.\n";
- 33 cout << "The party was about to give up all hope. ";
- 34 cout << "But while laying the deceased to rest, ";
- 35 cout << "they stumbled upon the buried fortune. ";
- 36 cout << "So the adventurers split " << GOLD_PIECES << " gold pieces. ";
- 37 cout << leader << " held on to the extra " << (GOLD_PIECES % survivors);
- 38 cout << " pieces to keep things fair of cource.\n";
- 39 return 0;
- 40 }
wang@wang:~/test$ g++ lost_fortune.cpp -o lost_fortunewang@wang:~/test$ ./lost_fortune Welcome to Lost FortunePlease enter the following for your personalized adventureEnter a number: 19Enter a number, smaller than the first: 13Enter your last name: wangA 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. 输入三个整数,输出它们的平均值
- 1 #include <iostream>
- 2 using namespace std;
- 3
- 4 int main()
- 5 {
- 6 int firstScore, secondScore, thirdScore;
- 7 cout << "Enter three integers: ";
- 8 cin >> firstScore >> secondScore >> thirdScore;
- 9 int average = (firstScore + secondScore + thirdScore) / 3;
- 10 cout << average << endl;
- 11 return 0;
- 12 }
wang@wang:~/test$ ./three_score Enter three integers: 1 2 32
Chapter 2: Truth, Branching, And The Game Loop: Guess My Number
(021) if (expression) statement;
- 1
- 2
- 3
- 4 #include <iostream>
- 5 using namespace std;
- 6
- 7 int main()
- 8 {
- 9 if (true) {
- 10 cout << "This is always displayd.\n";
- 11 }
- 12 if (false) {
- 13 cout << "This is never displayed.\n";
- 14 }
- 15
- 16 int score = 1000;
- 17 if (score) {
- 18 cout << "At least you didn't score zero.\n";
- 19 }
- 20 if (score > 250) {
- 21 cout << "You scored 250 more. Decent.\n";
- 22 }
- 23 if (score >= 500) {
- 24 cout << "You scored 500 or more. Nice.\n";
- 25 if (score >= 1000) {
- 26 cout << "You scored 1000 or more. Impressive!\n";
- 27 }
- 28 }
- 29 return 0;
- 30 }
wang@wang:~/test$ g++ score_rater.cpp -o score_raterwang@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 语句- 1
- 2
- 3
- 4 #include <iostream>
- 5 using namespace std;
- 6
- 7 int main()
- 8 {
- 9 int score;
- 10 cout << "Enter your score: ";
- 11 cin >> score;
- 12
- 13 if (score >= 1000) {
- 14 cout << "You scored 1000 or more. Impressive!\n";
- 15 } else {
- 16 cout << "You score less than 1000.\n";
- 17 }
- 18 return 0;
- 19 }
wang@wang:~/test$ ./score_rater2Enter your score: 456You score less than 1000.(023) 多个if语句- 1
- 2
- 3
- 4 #include <iostream>
- 5 using namespace std;
- 6
- 7 int main()
- 8 {
- 9 int score;
- 10 cout << "Enter your score: ";
- 11 cin >> score;
- 12
- 13 if (score >= 1000) {
- 14 cout << "You scored 1000 or more. Impressive!\n";
- 15 } else if (score >= 500) {
- 16 cout << "You score 500 or more. Nice.\n";
- 17 } else if (score >= 250) {
- 18 cout << "You score 250 or more. Decent.\n";
- 19 } else
- 20 cout << "You scored less than 250. Nothing to brag about.\n";
- 21 return 0;
- 22 }
wang@wang:~/test$ ./score_rater3 Enter your score: 100You scored less than 250. Nothing to brag about.(024) switch语句举例- 1
- 2
- 3
- 4 #include <iostream>
- 5 using namespace std;
- 6
- 7 int main()
- 8 {
- 9 cout << "Difficulty Levels\n";
- 10 cout << "1 - Easy\n";
- 11 cout << "2 - Normal\n";
- 12 cout << "3 - Hard\n";
- 13
- 14 int choice;
- 15 cout << "Choice: ";
- 16 cin >> choice;
- 17
- 18 switch (choice) {
- 19 case 1:
- 20 cout << "You picked Easy.\n";
- 21 break;
- 22 case 2:
- 23 cout << "You picked Normal.\n";
- 24 break;
- 25 case 3:
- 26 cout << "You picked Hard.\n";
- 27 default:
- 28 cout << "You made an illegal choice.\n";
- 29 }
- 30 return 0;
- 31 }
wang@wang:~/test$ ./menu_chooser Difficulty Levels1 - Easy2 - Normal3 - HardChoice: 2You picked Normal.(025) while 循环举例- 1
- 2
- 3
- 4 #include <iostream>
- 5 using namespace std;
- 6
- 7 int main()
- 8 {
- 9 char again = 'y';
- 10 while (again == 'y') {
- 11 cout << "**Played an exciting game**\n";
- 12 cout << "Do you want to play again? (y/n): ";
- 13 cin >> again;
- 14 }
- 15 cout << "Okay, bye.\n";
- 16 return 0;
- 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): bOkay, bye.(026) do while循环- 1
- 2
- 3
- 4 #include <iostream>
- 5 using namespace std;
- 6
- 7 int main()
- 8 {
- 9 char again;
- 10 do {
- 11 cout << "**Played an exciting game**";
- 12 cout << "\nDo you want to play again? (y/n): ";
- 13 cin >> again;
- 14 } while (again == 'y');
- 15
- 16 cout << "Okay, bye.\n";
- 17 return 0;
- 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): nOkay, bye.(027) break & continueYou can immediately exit a loop with the break statement, and you can jump directly to the top of a loop with a continue statement.
- 1
- 2
- 3
- 4 #include <iostream>
- 5 using namespace std;
- 6
- 7 int main()
- 8 {
- 9 int count = 0;
- 10 while (true) {
- 11 count += 1;
- 12
- 13 if (count > 10)
- 14 break;
- 15
- 16 if (count == 5)
- 17 continue;
- 18 cout << count << endl;
- 19 }
- 20 return 0;
- 21 }
wang@wang:~/test$ ./finicky_counter 1234678910(028) 逻辑运算符&& || !Logical NOT, ! has a higher level of precedence that logical AND, &&, which has a higher precedence than logical OR, ||.
- 1
- 2
- 3
- 4 #include <iostream>
- 5 #include <string>
- 6
- 7 using namespace std;
- 8
- 9 int main()
- 10 {
- 11 string username;
- 12 string password;
- 13 bool success;
- 14 cout << "\tGame Designer's Network\n";
- 15 do {
- 16 cout << "Username: ";
- 17 cin >> username;
- 18 cout << "Password: ";
- 19 cin >> password;
- 20
- 21 if (username == "S.Meier" && password == "civilization") {
- 22 cout << "Hey, Sid.\n";
- 23 success = true;
- 24 } else if (username == "S.Miyamoto" && password == "mariobros") {
- 25 cout << "What's up, Shigegu?\n";
- 26 success = true;
- 27 } else if (username == "guest" || password == "guest") {
- 28 cout << "Welcome, guest.\n";
- 29 success = true;
- 30 } else {
- 31 cout << "Your login failed.\n";
- 32 success = false;
- 33 }
- 34 } while (!success);
- 35 return 0;
- 36 }
wang@wang:~/test$ ./designers_network Game Designer's NetworkUsername: wangPassword: wangYour login failed.Username: wangPassword: guestWelcome, 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.
- 1
- 2
- 3
- 4 #include <iostream>
- 5 #include <cstdlib>
- 6 #include <ctime>
- 7 using namespace std;
- 8
- 9 int main()
- 10 {
- 11
- 12 srand(static_cast<unsigned int> (time(0)));
- 13 int randomNumber = rand();
- 14
- 15 int die = (randomNumber % 6) + 1;
- 16 cout << "You rolled a " << die << endl;
- 17 return 0;
- 18 }
wang@wang:~/test$ ./die_roller You rolled a 3wang@wang:~/test$ ./die_roller You rolled a 3wang@wang:~/test$ ./die_roller You rolled a 6(030) 猜数字游戏,适合三岁小孩子玩。- 1
- 2
- 3 #include <iostream>
- 4 #include <cstdlib>
- 5 #include <ctime>
- 6 using namespace std;
- 7
- 8 int main()
- 9 {
- 10
- 11 srand(static_cast<unsigned int>(time(0)));
- 12
- 13 int secretNumber = rand() % 100 + 1;
- 14 int tries = 0;
- 15 int guess;
- 16 cout << "\tWelcome to Guess My Number\n";
- 17 do {
- 18 cout << "Enter a guess: ";
- 19 cin >> guess;
- 20 ++tries;
- 21 if (guess > secretNumber)
- 22 cout << "Too high!\n";
- 23 else if (guess < secretNumber)
- 24 cout << "Too low!\n";
- 25 else
- 26 cout << "That's it! you got it in " << tries << " guesses!\n";
- 27 } while (guess != secretNumber);
- 28 return 0;
- 29 }
wang@wang:~/test$ ./guess_my_number Welcome to Guess My NumberEnter a guess: 56Too high!Enter a guess: 28Too high!Enter a guess: 14Too high!Enter a guess: 8Too high!Enter a guess: 4Too high!Enter a guess: 2Too low!Enter a guess: 3That's it! you got it in 7 guesses!(031) 习题
1. 使用enum表示。
- 1 #include <iostream>
- 2 using namespace std;
- 3
- 4 int main()
- 5 {
- 6 cout << "Difficult Levels\n";
- 7 cout << "1 - Easy\n";
- 8 cout << "2 - Normal\n";
- 9 cout << "3 - Hard\n";
- 10 enum level {EASY = 1, NORMAL, HARD};
- 11 int choice;
- 12 cout << "Choice: ";
- 13 cin >> choice;
- 14 switch (choice) {
- 15 case EASY:
- 16 cout << "You picked Easy.\n";
- 17 break;
- 18 case NORMAL:
- 19 cout << "You picked Normal.\n";
- 20 break;
- 21 case HARD:
- 22 cout << "You picked Hard.\n";
- 23 default:
- 24 cout << "You made an illegal choice.\n";
- 25 }
- 26 return 0;
- 27 }
wang@wang:~/test$ ./menulevel Difficult Levels1 - Easy2 - Normal3 - HardChoice: 2You picked Normal.2. 没有进入while循环中。
3. 用户提供数据,电脑猜
- 1
- 2
- 3 #include <iostream>
- 4 #include <cstdlib>
- 5 #include <ctime>
- 6 using namespace std;
- 7
- 8 int main()
- 9 {
- 10 int number;
- 11 cout << "Enter a number (1 - 10): ";
- 12 cin >> number;
- 13 int tries = 0;
- 14 int guess;
- 15 cout << "\tWelcome to Guess My Number\n";
- 16 do {
- 17
- 18 srand(static_cast<unsigned int>(time(0)));
- 19
- 20 guess = rand() % 10 + 1;
- 21 ++tries;
- 22 if (guess > number)
- 23 cout << "Too high!\n";
- 24 else if (guess < number)
- 25 cout << "Too low!\n";
- 26 else
- 27 cout << "That's it! you got it in " << tries << " guesses!\n";
- 28 } while (guess != number);
- 29 return 0;
- 30 }
随机猜猜的次数太多。That's it! you got it in 300166 guesses!
Chapter 3: For Loops, Strings, And Arrays: Word Jumble
(032) for循环
- 1
- 2
- 3
- 4 #include <iostream>
- 5 using namespace std;
- 6
- 7 int main()
- 8 {
- 9 cout << "Count forward: ";
- 10 for (int i = 0; i < 10; ++i)
- 11 cout << i << " ";
- 12 cout << "\nCounting backward: ";
- 13 for (int i = 9; i >= 0; --i)
- 14 cout << i << " ";
- 15 cout << "\nCounting by fives: ";
- 16 for (int i = 0; i <= 50; i += 5)
- 17 cout << i << " ";
- 18 cout << "\nCounting with null statements: ";
- 19 int count = 0;
- 20 for (; count < 10;) {
- 21 cout << count << " ";
- 22 ++count;
- 23 }
- 24 cout << "\nCounting with nested for loops:\n";
- 25 const int ROWS = 5;
- 26 const int COLUMNS = 3;
- 27 for (int i = 0; i < ROWS; ++i) {
- 28 for (int j = 0; j < COLUMNS; ++j) {
- 29 cout << i << "," << j << " ";
- 30 }
- 31 cout << endl;
- 32 }
- 33 return 0;
- 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.
- 1
- 2
- 3
- 4 #include <iostream>
- 5 #include <string>
- 6 using namespace std;
- 7
- 8 int main()
- 9 {
- 10 string word1 = "Game";
- 11 string word2("Over");
- 12 string word3(3, '!');
- 13
- 14 string phrase = word1 + " " + word2 + word3;
- 15 cout << "The phrase is: " << phrase << "\n";
- 16 cout << "The phrase has " << phrase.size() << " characters in it.\n";
- 17 cout << "The character at position 0 is: " << phrase[0] << "\n";
- 18 cout << "Changing the character at position 0.\n";
- 19 phrase[0] = 'L';
- 20 cout << "The phrase is now: " << phrase << "\n";
- 21 for (unsigned int i = 0; i < phrase.size(); ++i)
- 22 cout << "Character at position " << i << " is: " << phrase[i] << "\n";
- 23 cout << "The sequence 'Over' begins at location ";
- 24 cout << phrase.find("Over") << endl;
- 25 if (phrase.find("eggplant") == string::npos)
- 26 cout << "'eggplant' is not in the phrase.\n";
- 27 phrase.erase(4, 5);
- 28 cout << "The phrase is now: " << phrase << endl;
- 29 phrase.erase(4);
- 30 cout << "The phrase is now: " << phrase << endl;
- 31 phrase.erase();
- 32 cout << "The phrase is now: " << phrase << endl;
- 33 if (phrase.empty())
- 34 cout << "The phrase is no more.\n";
- 35 return 0;
- 36 }
wang@wang:~/test$ ./string_tester The phrase is: Game Over!!!The phrase has 12 characters in it.The character at position 0 is: GChanging the character at position 0.The phrase is now: Lame Over!!!Character at position 0 is: LCharacter at position 1 is: aCharacter at position 2 is: mCharacter at position 3 is: eCharacter at position 4 is: Character at position 5 is: OCharacter at position 6 is: vCharacter at position 7 is: eCharacter at position 8 is: rCharacter 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: LameThe phrase is now: The phrase is no more.(034) 英雄复仇游戏主要讲述携带的装备情况
- 1
- 2
- 3
- 4 #include <iostream>
- 5 #include <string>
- 6 using namespace std;
- 7
- 8 int main()
- 9 {
- 10 const int MAX_ITEMS = 10;
- 11 string inventory[MAX_ITEMS];
- 12 int numItems = 0;
- 13 inventory[numItems++] = "sword";
- 14 inventory[numItems++] = "armor";
- 15 inventory[numItems++] = "shield";
- 16 cout << "Your items:\n";
- 17 for (int i = 0; i < numItems; i++)
- 18 cout << inventory[i] << endl;
- 19 cout << "You trade your sword for a battle axe.\n";
- 20 inventory[0] = "battle axe";
- 21 for (int i = 0; i < numItems; ++i)
- 22 cout << inventory[i] << endl;
- 23 cout << "The item name '" << inventory[0] << "' has ";
- 24 cout << inventory[0].size() << " letters in it.\n";
- 25 cout << "You find a healing potion.\n";
- 26 if (numItems < MAX_ITEMS)
- 27 inventory[numItems++] = "healing portion";
- 28 else
- 29 cout << "You have too many items and can't carry another.\n";
- 30 for (int i = 0; i < numItems; ++i)
- 31 cout << inventory[i] << endl;
- 32 return 0;
- 33 }
wang@wang:~/test$ ./heros_inventory Your items:swordarmorshieldYou trade your sword for a battle axe.battle axearmorshieldThe item name 'battle axe' has 10 letters in it.You find a healing potion.battle axearmorshieldhealing 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游戏
- 1
- 2
- 3
- 4 #include <iostream>
- 5 using namespace std;
- 6
- 7 int main()
- 8 {
- 9 const int ROWS = 3;
- 10 const int COLUMNS = 3;
- 11 char board[ROWS][COLUMNS] = {{'O', 'X', 'O'}, {' ', 'X', 'X'}, {'X', 'O', 'O'}};
- 12 cout << "Here's the tic-tac-toe board:\n";
- 13 for (int i = 0; i < ROWS; i++) {
- 14 for (int j = 0; j < COLUMNS; ++j)
- 15 cout << board[i][j];
- 16 cout << endl;
- 17 }
- 18 cout << "'X' moves to the empty location.\n";
- 19 board[1][0] = 'X';
- 20 cout << "Now the tic-tac-toe board is:\n";
- 21 for (int i = 0; i < ROWS; i++) {
- 22 for(int j = 0; j < COLUMNS; ++j)
- 23 cout << board[i][j];
- 24 cout << endl;
- 25 }
- 26 cout << "'X' wins!\n";
- 27 return 0;
- 28 }
wang@wang:~/test$ ./tic-tac-toe_board Here's the tic-tac-toe board:OXO XXXOO'X' moves to the empty location.Now the tic-tac-toe board is:OXOXXXXOO'X' wins!(037) 猜字游戏把单词打乱,然后根据提示猜是什么单词。
-
-
- #include <iostream>
- #include <string>
- #include <cstdlib>
- #include <ctime>
- using namespace std;
-
- int main()
- {
- enum field {WORD, HINT, NUM_FIELDS};
- const int NUM_WORDS = 5;
- const string WORDS[NUM_WORDS][NUM_FIELDS] = {
- {"wall", "Do you feel you're banging your head against something?"},
- {"glasses", "These might help you see the answer."},
- {"labored", "Going slowly, is it?"},
- {"persistent", "Keep at it."},
- {"jumble", "It's what the game is all about."}};
- srand(static_cast<unsigned int>(time(0)));
- int choice = rand() % NUM_WORDS;
- string theWord = WORDS[choice][WORD];
- string theHint = WORDS[choice][HINT];
-
- string jumble = theWord;
- int length = jumble.size();
- for (int i = 0; i < length; ++i) {
- int index1 = (rand() % length);
- int index2 = (rand() % length);
- char temp = jumble[index1];
- jumble[index1] = jumble[index2];
- jumble[index2] = temp;
- }
- cout << "\t\tWelcome to Word Jumble!\n";
- cout << "Unscramble the letters to make a word.\n";
- cout << "Enter 'hint' for a hint.\n";
- cout << "Enter 'quit' to quit the game.\n";
- cout << "The jumble is: " << jumble;
- string guess;
- cout << "\nyou guess: ";
- cin >> guess;
- while ((guess != theWord) && (guess != "quit")) {
- if(guess == "hint")
- cout << theHint;
- else
- cout << "Sorry, that's not it.";
- cout << "\nYour guess: ";
- cin >> guess;
- }
- if (guess == theWord)
- cout << "That's it! You guess it!\n";
- cout << "Thanks for playing.\n";
- return 0;
- }
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: eetpsitsnryou guess: hintKeep at it.Your guess: persistentThat'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. 增加计数的效果
- cin >> guess;
- 41 int count = 1;
- 42 while ((guess != theWord) && (guess != "quit")) {
- 43 if(guess == "hint")
- 44 cout << theHint;
- 45 else
- 46 cout << "Sorry, that's not it.";
- 47 cout << "\nYour guess: ";
- 48 cin >> guess;
- 49 ++count;
- 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举例
- 1 // Hero's Inventory 2.0
- 2 // Demonstrates vectors
- 3
- 4 #include <iostream>
- 5 #include <string>
- 6 #include <vector>
- 7 using namespace std;
- 8
- 9 int main()
- 10 {
- 11 vector<string> inventory;
- 12 inventory.push_back("sword");
- 13 inventory.push_back("armor");
- 14 inventory.push_back("shield");
- 15 cout << "You have " << inventory.size() << " items.\n";
- 16 cout << "Your items:\n";
- 17 for (unsigned int i = 0; i < inventory.size(); ++i)
- 18 cout << inventory[i] << endl;
- 19 cout << "You trade your sword for a battle axe.";
- 20 inventory[0] = "battle axe";
- 21 cout << "Your items:\n";
- 22 for (unsigned int i = 0; i < inventory.size(); ++i)
- 23 cout << inventory[i] << endl;
- 24 cout << "The item name '" << inventory[0] << "' has ";
- 25 cout << inventory[0].size() << " letters in it.\n";
- 26 cout << "your shield is destroyed in a fierce battle.";
- 27 inventory.pop_back();
- 28 cout << "Your items:\n";
- 29 for (unsigned int i = 0; i < inventory.size(); ++i)
- 30 cout << inventory[i] << endl;
- 31 cout << "You were robbed of all of your possessions by a thief.\n";
- 32 inventory.clear();
- 33 if (inventory.empty())
- 34 cout << "You have nothing.\n";
- 35 else
- 36 cout << "You have at least one item.\n";
- 37 return 0;
- 38 }
wang@wang:~/workspace/beginc++game$ ./heros_inventory2 You have 3 items.Your items:swordarmorshieldYou trade your sword for a battle axe.Your items:battle axearmorshieldThe item name 'battle axe' has 10 letters in it.your shield is destroyed in a fierce battle.Your items:battle axearmorYou were robbed of all of your possessions by a thief.You have nothing.(042) 迭代器举例
- 1
- 2
- 3 #include <iostream>
- 4 #include <string>
- 5 #include <vector>
- 6 using namespace std;
- 7
- 8 int main()
- 9 {
- 10 vector<string> inventory;
- 11 inventory.push_back("sword");
- 12 inventory.push_back("armor");
- 13 inventory.push_back("shield");
- 14 vector<string>::iterator myIterator;
- 15 vector<string>::const_iterator iter;
- 16 cout << "Your items:\n";
- 17 for (iter = inventory.begin(); iter != inventory.end(); ++iter)
- 18 cout << *iter << endl;
- 19 cout << "You trade your sword for a battle axe.\n";
- 20 myIterator = inventory.begin();
- 21 *myIterator = "battle axe";
- 22 cout << "Your items:\n";
- 23 for (iter = inventory.begin(); iter != inventory.end(); ++iter)
- 24 cout << *iter << endl;
- 25 cout << "The item name '" << *myIterator << "' has ";
- 26 cout << (*myIterator).size() << " letters in it.\n";
- 27 cout << "The item name '" << *myIterator << "' has ";
- 28 cout << myIterator->size() << " letters in it.\n";
- 29 cout << "You recover a corssbox from a slain enemy.\n";
- 30 inventory.insert(inventory.begin(), "crossbox");
- 31 cout << "Your items:\n";
- 32 for (iter = inventory.begin(); iter != inventory.end(); ++iter)
- 33 cout << *iter << endl;
- 34 cout << "Your armor is destoryed in a fierce battle.\n";
- 35 inventory.erase(inventory.begin() + 2);
- 36 cout << "Your items:\n";
- 37 for (iter = inventory.begin(); iter != inventory.end(); ++iter)
- 38 cout << *iter << endl;
- 39 return 0;
- 40 }
wang@wang:~/test$ ./heros_inventory3 Your items:swordarmorshieldYou trade your sword for a battle axe.Your items:battle axearmorshieldThe 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:crossboxbattle axearmorshieldYour armor is destoryed in a fierce battle.Your items:crossboxbattle axeshield(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.
- 1
- 2
- 3 #include <iostream>
- 4 #include <vector>
- 5 #include <algorithm>
- 6 #include <ctime>
- 7 #include <cstdlib>
- 8 using namespace std;
- 9
- 10 int main()
- 11 {
- 12 vector<int>::const_iterator iter;
- 13 cout << "Creating a list of scores.\n";
- 14 vector<int> scores;
- 15 scores.push_back(1500);
- 16 scores.push_back(3500);
- 17 scores.push_back(7500);
- 18
- 19 cout << "High Scores:\n";
- 20 for (iter = scores.begin(); iter != scores.end(); ++iter)
- 21 cout << *iter << endl;
- 22 cout << "Finding a score:\n";
- 23 int score;
- 24 cout << "Enter a score to find: ";
- 25 cin >> score;
- 26 iter = find(scores.begin(), scores.end(), score);
- 27 if (iter != scores.end())
- 28 cout << "Score found.\n";
- 29 else
- 30 cout << "Score not found.\n";
- 31 cout << "Randomizing scores.\n";
- 32 srand(static_cast<unsigned int>(time(0)));
- 33 random_shuffle(scores.begin(), scores.end());
- 34 cout << "High Scores:\n";
- 35 for (iter = scores.begin(); iter != scores.end(); ++iter)
- 36 cout << *iter << endl;
- 37 cout << "Sorting scores.\n";
- 38 sort(scores.begin(), scores.end());
- 39 cout << "High Scores:\n";
- 40 for (iter = scores.begin(); iter != scores.end(); ++iter)
- 41 cout << *iter << endl;
- 42 return 0;
- 43 }
wang@wang:~/test$ ./high_scores Creating a list of scores.High Scores:150035007500Finding a score:Enter a score to find: 7500Score found.Randomizing scores.High Scores:750035001500Sorting scores.High Scores:150035007500(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) 伪代码举例
比较经典的例子,猜字游戏,只有八次机会;
刚开始的时候可以乱猜,后来根据已知的字符猜未知的字符。
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #include <iostream>
- #include <string>
- #include <vector>
- #include <algorithm>
- #include <ctime>
- #include <cctype>
-
- using namespace std;
-
- int main(int argc, char *argv[])
- {
-
-
- const int MAX_WRONG = 8;
- vector<string> words;
- words.push_back("GUESS");
- words.push_back("HANGMAN");
- words.push_back("DIFFICULT");
- srand(static_cast<unsigned int>(time(0)));
- random_shuffle(words.begin(), words.end());
- const string THE_WORD = words[0];
-
- int wrong = 0;
-
- string soFar(THE_WORD.size(), '-');
-
- string used = "";
-
- cout << "Welcome to Hangman. Good luck!\n";
-
-
- while ((wrong < MAX_WRONG) && (soFar != THE_WORD)) {
- cout << "You have " << (MAX_WRONG - wrong) << " incorrect guesses left.\n";
- cout << "You have used the following letters: " << used << endl;
- cout << "So far, the word is: " << soFar << endl;
- char guess;
- cout << "Enter your guess: ";
- cin >> guess;
-
- guess = toupper(guess);
- while (used.find(guess) != string::npos) {
- cout << "You have already guessed " << guess << endl;
- cout << "Enter your guess: ";
- cin >> guess;
- guess = toupper(guess);
- }
- used += guess;
- if (THE_WORD.find(guess) != string::npos) {
- cout << "That's right! " << guess << " is in the word.\n";
-
- for (int i = 0; i < THE_WORD.size(); ++i)
- if (THE_WORD[i] == guess)
- soFar[i] = guess;
- } else {
- cout << "Sorry, " << guess << " isn't in the word.\n";
- ++wrong;
- }
- }
-
- if (wrong == MAX_WRONG)
- cout << "You have been hanged!\n";
- else
- cout << "You guess it!\n";
- cout << "The word was " << THE_WORD << endl;
-
- return 0;
- }
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包括你喜欢的游戏
- 1 #include <algorithm>
- 2 #include <iostream>
- 3 #include <vector>
- 4 using namespace std;
- 5
- 6 int main()
- 7 {
- 8 vector<string> games;
- 9 vector<string>::iterator iter;
- 10 games.push_back("war world");
- 11 games.push_back("person vender");
- 12 iter = games.begin();
- 13 games.insert(iter, "hello world");
- 14 for (iter = games.begin(); iter != games.end(); ++iter)
- 15 cout << *iter << endl;
- 16 return 0;
- 17 }
wang@wang:~/test$ ./list_game hello worldwar worldperson vender2. 每次都是调过一个数据,没有每个都遍历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) 函数简单举例
- 1
- 2
- 3 #include <iostream>
- 4 using namespace std;
- 5
- 6
- 7 void instruction();
- 8
- 9 int main()
- 10 {
- 11 instruction();
- 12 return 0;
- 13 }
- 14
- 15
- 16 void instruction() {
- 17 cout << "Welcome to the most fun you've ever had with text!\n";
- 18 cout << "Here's how to play the game...\n";
- 19 }
wang@wang:~/test$ ./instructions Welcome to the most fun you've ever had with text!Here's how to play the game...(050) 第二个例子,传递参数
- 1
- 2
- 3
- 4 #include <iostream>
- 5 #include <string>
- 6 using namespace std;
- 7
- 8 char askYesNo1();
- 9 char askYesNo2(string question);
- 10
- 11 int main()
- 12 {
- 13 char answer1 = askYesNo1();
- 14 cout << "Thank you for answering: " << answer1 << "\n";
- 15 char answer2 = askYesNo2("Do you wish to save your game?");
- 16 cout << "Thanks for answering: " << answer2 << "\n";
- 17 return 0;
- 18 }
- 19
- 20 char askYesNo1() {
- 21 char response1;
- 22 do {
- 23 cout << "Please enter 'y' or 'n': ";
- 24 cin >> response1;
- 25 } while(response1 != 'y' && response1 != 'n');
- 26 return response1;
- 27 }
- 28
- 29 char askYesNo2(string question) {
- 30 char response2;
- 31 do {
- 32 cout << question << " (y/n): ";
- 33 cin >> response2;
- 34 } while (response2 != 'y' && response2 != 'n');
- 35 return response2;
- 36 }
wang@wang:~/test$ ./yes_or_no Please enter 'y' or 'n': nThank you for answering: nDo you wish to save your game? (y/n): yThanks 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.
- 1
- 2
- 3 #include <iostream>
- 4 using namespace std;
- 5 void func();
- 6 int main()
- 7 {
- 8
- 9 int var = 5;
- 10 cout << "In main() var is: " << var << "\n";
- 11 func();
- 12 cout << "Back in main() var is: " << var << endl;
- 13 {
- 14 cout << "In main() in a new scope var is: " << var << endl;
- 15 cout << "Creating new var in new scope.\n";
- 16
- 17 int var = 10;
- 18 cout << "In main() in a new scope var is: " << var << "\n";
- 19 }
- 20 cout << "At end of main() var created in new scope no longer exists.\n";
- 21 cout << "At end of main() var is: " << var << "\n";
- 22 return 0;
- 23 }
- 24
- 25 void func()
- 26 {
- 27 int var = -5;
- 28 cout << "In func() var is: " << var << "\n";
- 29 }
wang@wang:~/test$ ./scoping In main() var is: 5In func() var is: -5Back in main() var is: 5In main() in a new scope var is: 5Creating new var in new scope.In main() in a new scope var is: 10At end of main() var created in new scope no longer exists.At end of main() var is: 5(053) 全局变量举例- 1
- 2
- 3 #include <iostream>
- 4 using namespace std;
- 5
- 6 int glob = 10;
- 7 void access_global();
- 8 void hide_global();
- 9 void change_global();
- 10 int main()
- 11 {
- 12 cout << "In main() glob is: " << glob << "\n";
- 13 access_global();
- 14 hide_global();
- 15 cout << "In main() glob is: " << glob << endl;
- 16 change_global();
- 17 cout << "In main() glob is: " << glob << endl;
- 18 return 0;
- 19 }
- 20
- 21 void access_global() {
- 22 cout << "In access_global() glob is: " << glob << endl;
- 23 }
- 24
- 25 void hide_global() {
- 26
- 27 int glob = 0;
- 28 cout << "In hide_global() glob is: " << glob << endl;
- 29 }
- 30
- 31 void change_global() {
- 32 glob = -10;
- 33 cout << "In change_global() glob is: " << glob << "\n";
- 34 }
wang@wang:~/test$ ./global_reach In main() glob is: 10In access_global() glob is: 10In hide_global() glob is: 0In main() glob is: 10In change_global() glob is: -10In 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) 默认参数
- 1
- 2
- 3 #include <iostream>
- 4 #include <string>
- 5 using namespace std;
- 6
- 7 int askNumber(int high, int low = 1);
- 8
- 9 int main()
- 10 {
- 11 int number = askNumber(5);
- 12 cout << "Thanks for entering: " << number << "\n";
- 13 number = askNumber(10, 5);
- 14 cout << "Thanks for entering: " << number << "\n";
- 15 return 0;
- 16 }
- 17
- 18 int askNumber(int high, int low) {
- 19 int num;
- 20 do {
- 21 cout << "Please enter a number (" << low << " - " << high << "): ";
- 22 cin >> num;
- 23 } while (num > high || num < low);
- 24 return num;
- 25 }
wang@wang:~/test$ ./give_me_a_number Please enter a number (1 - 5): 3Thanks for entering: 3Please enter a number (5 - 10): 6Thanks for entering: 6(056) 重载函数- 1
- 2
- 3 #include <iostream>
- 4 #include <string>
- 5 using namespace std;
- 6 int triple(int number);
- 7 string triple(string text);
- 8
- 9 int main()
- 10 {
- 11 cout << "Tripling 5: " << triple(5) << "\n";
- 12 cout << "Tripling 'gamer': " << triple("gamer") << "\n";
- 13 return 0;
- 14 }
- 15
- 16 int triple(int number) {
- 17 return (number * 3);
- 18 }
- 19
- 20 string triple(string text) {
- 21 return (text + text + text);
- 22 }
wang@wang:~/test$ ./triple Tripling 5: 15Tripling 'gamer': gamergamergamer(057) 内联函数内联函数和默认参数相反,默认参数是在生命中,内联函数是在定义中。
- 1
- 2
- 3 #include <iostream>
- 4 int radiation(int health);
- 5 using namespace std;
- 6
- 7 int main()
- 8 {
- 9 int health = 80;
- 10 cout << "Your health is " << health << "\n";
- 11 health = radiation(health);
- 12 cout << "After radiation exposure your health is " << health << endl;
- 13 health = radiation(health);
- 14 cout << "After radiation exposure your health is " << health << endl;
- 15 health = radiation(health);
- 16 cout << "After radiation exposure your health is " << health << endl;
- 17 return 0;
- 18 }
- 19
- 20 inline int radiation(int health) {
- 21 return (health / 2);
- 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) 综合举例
-
-
- #include <iostream>
- #include <string>
- using namespace std;
- string askText(string prompt);
- int askNumber(string prompt);
- void tellStory(string name, string noun, int number, string bodyPart, string verb);
-
- int main()
- {
- cout << "Welcome to Mad Lib.\n";
- cout << "Answer the following questions to help create a new story.\n";
- string name = askText("Please enter a name: ");
- string noun = askText("Please enter a plural noun: ");
- int number = askNumber("Please enter a number: ");
- string bodyPart = askText("Please enter a body part: ");
- string verb = askText("Please enter a verb: ");
- tellStory(name, noun, number, bodyPart, verb);
- return 0;
- }
-
- string askText(string prompt)
- {
- string text;
- cout << prompt;
- cin >> text;
- return text;
- }
-
- int askNumber(string prompt)
- {
- int num;
- cout << prompt;
- cin >> num;
- return num;
- }
-
- void tellStory(string name, string noun, int number, string bodyPart, string verb)
- {
- cout << "Here's your story:\n";
- cout << "The famous explorer " << name;
- cout << " had nearly given up a life-long quest to find.\n";
- cout << "The Lost City of " << noun << " when one day, the " << noun;
- cout << " found the explorer.\n";
- cout << "Surrounded by " << number << " " << noun;
- cout << ", a tear came to " << name << "'s " << bodyPart << ".\n";
- cout << "After all this time, the quest was finally over. ";
- cout << "And then, then " << noun << endl;
- cout << "promptly devoured ";
- cout << name << ". ";
- cout << "The moral of the story? Be careful what you " << verb << " for.\n";
- }
wang@wang:~/test$ ./mad_lib Welcome to Mad Lib.Answer the following questions to help create a new story.Please enter a name: wangPlease enter a plural noun: wangPlease enter a number: 4Please enter a body part: headPlease enter a verb: doHere'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 wangpromptly devoured wang. The moral of the story? Be careful what you dofor.(059) 习题1. 默认参数放在函数生命最后。
2. Two function, one for input, another for judge.
-
-
- #include <iostream>
- #include <string>
- #include <vector>
- #include <algorithm>
- #include <ctime>
- #include <cctype>
-
- using namespace std;
-
- char guesschar() {
- char guess;
- cout << "Enter your guess: ";
- cin >> guess;
-
- guess = toupper(guess);
- return guess;
- }
-
- bool include(char c, string word) {
- for (int i = 0; i < word.size(); ++i)
- if (c == word[i])
- return true;
- }
-
- int main(int argc, char *argv[])
- {
-
-
- const int MAX_WRONG = 8;
- vector<string> words;
- words.push_back("GUESS");
- words.push_back("HANGMAN");
- words.push_back("DIFFICULT");
- srand(static_cast<unsigned int>(time(0)));
- random_shuffle(words.begin(), words.end());
- const string THE_WORD = words[0];
-
- int wrong = 0;
-
- string soFar(THE_WORD.size(), '-');
-
- string used = "";
-
- cout << "Welcome to Hangman. Good luck!\n";
-
-
- while ((wrong < MAX_WRONG) && (soFar != THE_WORD)) {
- cout << "You have " << (MAX_WRONG - wrong) << " incorrect guesses left.\n";
- cout << "You have used the following letters: " << used << endl;
- cout << "So far, the word is: " << soFar << endl;
- char guess = guesschar();
- while (used.find(guess) != string::npos) {
- cout << "You have already guessed " << guess << endl;
- guess = getchar();
- }
- used += guess;
- if (include(guess, THE_WORD)) {
- cout << "That's right! " << guess << " is in the word.\n";
-
- for (int i = 0; i < THE_WORD.size(); ++i)
- if (THE_WORD[i] == guess)
- soFar[i] = guess;
- } else {
- cout << "Sorry, " << guess << " isn't in the word.\n";
- ++wrong;
- }
- }
-
- if (wrong == MAX_WRONG)
- cout << "You have been hanged!\n";
- else
- cout << "You guess it!\n";
- cout << "The word was " << THE_WORD << endl;
-
- return 0;
- }
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: EThat's right! E is in the word.You have 8 incorrect guesses left.You have used the following letters: ESo far, the word is: --E--Enter your guess: FSorry, F isn't in the word.You have 7 incorrect guesses left.You have used the following letters: EFSo far, the word is: --E--Enter your guess: DSorry, D isn't in the word.You have 6 incorrect guesses left.You have used the following letters: EFDSo far, the word is: --E--Enter your guess: SThat's right! S is in the word.You have 6 incorrect guesses left.You have used the following letters: EFDSSo far, the word is: --ESSEnter your guess: GThat's right! G is in the word.You have 6 incorrect guesses left.You have used the following letters: EFDSGSo far, the word is: G-ESSEnter your guess: EYou have already guessed ESorry, isn't in the word.You have 5 incorrect guesses left.You have used the following letters: EFDSGSo far, the word is: G-ESSEnter your guess: UThat's right! U is in the word.You guess it!The word was GUESSPress <RETURN> to close this window...
3. default argument
- 1 #include <iostream>
- 2 #include <string>
- 3 using namespace std;
- 4
- 5 int getNumber(string str = "Get an int: ");
- 6 int main()
- 7 {
- 8 int i = getNumber();
- 9 int j = getNumber("Get an number: ");
- 10 cout << i << " " << j << endl;
- 11 return 0;
- 12 }
- 13
- 14 int getNumber(string str) {
- 15 cout << str;
- 16 int n;
- 17 cin >> n;
- 18 return n;
- 19 }
wang@wang:~/test$ ./default_arg Get an int: 4Get an number: 54 5
Chapter 6: References: Tic-Tac-Toe
(060) 引用,引用的简单举例
- 1
- 2
- 3 #include<iostream>
- 4 using namespace std;
- 5
- 6 int main()
- 7 {
- 8 int myScore = 1000;
- 9
- 10 int &mikesScore = myScore;
- 11 cout << "myScore is: " << myScore << endl;
- 12 cout << "mikesScore is: " << mikesScore << endl;
- 13 cout << "Adding 500 to myScore\n";
- 14 myScore += 500;
- 15 cout << "myScore is: " << myScore << endl;
- 16 cout << "mikesScore is: " << mikesScore << endl;
- 17 cout << "Adding 500 to mikesScore\n";
- 18 mikesScore += 500;
- 19 cout << "myScore is: " << myScore << endl;
- 20 cout << "mikesScore is: " << mikesScore << endl;
- 21 return 0;
- 22 }
wang@wang:~/test$ ./referencing myScore is: 1000mikesScore is: 1000Adding 500 to myScoremyScore is: 1500mikesScore is: 1500Adding 500 to mikesScoremyScore is: 2000mikesScore is: 2000(061) 通过引用修改原来变量举例- 1
- 2
- 3 #include <iostream>
- 4 using namespace std;
- 5
- 6 void badSwap(int x, int y);
- 7 void goodSwap(int &x, int &y);
- 8 int main()
- 9 {
- 10 int myScore = 150;
- 11 int yourScore = 1000;
- 12 cout << "Original values\n";
- 13 cout << "myScore: " << myScore << endl;
- 14 cout << "yourScore: " << yourScore << endl;
- 15 cout << "Calling badSwap()\n";
- 16 badSwap(myScore, yourScore);
- 17 cout << "myScore: " << myScore << endl;
- 18 cout << "yourScore: " << yourScore << endl;
- 19 cout << "Calling goodSwap()\n";
- 20 goodSwap(myScore, yourScore);
- 21 cout << "myScore: " << myScore << endl;
- 22 cout << "yourScore: " << yourScore << endl;
- 23 return 0;
- 24 }
- 25
- 26 void badSwap(int x, int y) {
- 27 int temp = x;
- 28 x = y;
- 29 y = temp;
- 30 }
- 31
- 32 void goodSwap(int &x, int &y) {
- 33 int temp = x;
- 34 x = y;
- 35 y = temp;
- 36 }
wang@wang:~/test$ ./swap Original valuesmyScore: 150yourScore: 1000Calling badSwap()myScore: 150yourScore: 1000Calling goodSwap()myScore: 1000yourScore: 150(062) 利用引用可以减少拷贝- 1
- 2
- 3 #include <iostream>
- 4 #include <string>
- 5 #include <vector>
- 6 using namespace std;
- 7
- 8 void display(const vector<string> &inventory);
- 9 int main()
- 10 {
- 11 vector<string> inventory;
- 12 inventory.push_back("sword");
- 13 inventory.push_back("armor");
- 14 inventory.push_back("shield");
- 15 display(inventory);
- 16 return 0;
- 17 }
- 18
- 19
- 20 void display(const vector<string> &vec)
- 21 {
- 22 cout << "Your items:\n";
- 23 for (vector<string>::const_iterator iter = vec.begin();
- 24 iter != vec.end(); ++iter)
- 25 cout << *iter << endl;
- 26 }
wang@wang:~/test$ ./inventory_displayer Your items:swordarmorshield(063) 返回引用- 1
- 2
- 3 #include <iostream>
- 4 #include <string>
- 5 #include <vector>
- 6 using namespace std;
- 7
- 8 string & refToElement(vector<string> &inventory, int i);
- 9 int main()
- 10 {
- 11 vector<string> inventory;
- 12 inventory.push_back("sword");
- 13 inventory.push_back("armor");
- 14 inventory.push_back("shield");
- 15
- 16 cout << "Sending the returned reference to cout:\n";
- 17 cout << refToElement(inventory, 0) << "\n";
- 18
- 19 cout << "Assigning the returned reference to another reference.\n";
- 20 string &rStr = refToElement(inventory, 1);
- 21 cout << "Send the new reference to cout:\n";
- 22 cout << rStr << endl;
- 23
- 24 cout << "Assigning the returned reference to a string object.\n";
- 25 string str = refToElement(inventory, 2);
- 26 cout << "Sending the new string object to cout:\n";
- 27 cout << str << endl;
- 28
- 29 cout << "Altering an object through a returned reference.\n";
- 30 rStr = "Healing Potion";
- 31 cout << "Sending the altered object to cout:\n";
- 32 cout << inventory[1] << endl;
- 33 return 0;
- 34 }
- 35
- 36 string & refToElement(vector<string> &vec, int i)
- 37 {
- 38 return vec[i];
- 39 }
wang@wang:~/test$ ./inventory_referencer Sending the returned reference to cout:swordAssigning the returned reference to another reference.Send the new reference to cout:armorAssigning the returned reference to a string object.Sending the new string object to cout:shieldAltering an object through a returned reference.Sending the altered object to cout:Healing Potion(064) 这个例子有难度,自己编写没有成功,有点惭愧,贴出作者写的代码。
我觉得是一个初学者比较容易学会的游戏。
其中还涉及到计算机怎么走更合适。
第一,如果计算机下步能赢,就把棋子下在那一步;
第二,如果下步人类会赢,就把棋子下在人类那一步;
第三,根据棋盘剩余的最好的位置下子,第一个最好的位置是正中间。
-
-
-
- #include <iostream>
- #include <string>
- #include <vector>
- #include <algorithm>
-
- using namespace std;
-
-
- const char X = 'X';
- const char O = 'O';
- const char EMPTY = ' ';
- const char TIE = 'T';
- const char NO_ONE = 'N';
-
-
-
- void instructions();
-
- char askYesNo(string question);
-
- int askNumber(string question, int high, int low = 0);
-
- char humanPiece();
-
- char opponent(char piece);
-
- void displayBoard(const vector<char>& board);
-
- char winner(const vector<char>& board);
-
- bool isLegal(const vector<char>& board, int move);
-
- int humanMove(const vector<char>& board, char human);
-
- int computerMove(vector<char> board, char computer);
-
- void announceWinner(char winner, char computer, char human);
-
-
- int main()
- {
- int move;
- const int NUM_SQUARES = 9;
- vector<char> board(NUM_SQUARES, EMPTY);
-
- instructions();
- char human = humanPiece();
- char computer = opponent(human);
- char turn = X;
- displayBoard(board);
-
- while (winner(board) == NO_ONE)
- {
- if (turn == human)
- {
- move = humanMove(board, human);
- board[move] = human;
- }
- else
- {
- move = computerMove(board, computer);
- board[move] = computer;
- }
- displayBoard(board);
- turn = opponent(turn);
- }
-
- announceWinner(winner(board), computer, human);
-
- return 0;
- }
-
-
- void instructions()
- {
- cout << "Welcome to the ultimate man-machine showdown: Tic-Tac-Toe.\n";
- cout << "--where human brain is pit against silicon processor\n\n";
-
- cout << "Make your move known by entering a number, 0 - 8. The number\n";
- cout << "corresponds to the desired board position, as illustrated:\n\n";
-
- cout << " 0 | 1 | 2\n";
- cout << " ---------\n";
- cout << " 3 | 4 | 5\n";
- cout << " ---------\n";
- cout << " 6 | 7 | 8\n\n";
-
- cout << "Prepare yourself, human. The battle is about to begin.\n\n";
- }
-
- char askYesNo(string question)
- {
- char response;
- do
- {
- cout << question << " (y/n): ";
- cin >> response;
- } while (response != 'y' && response != 'n');
-
- return response;
- }
-
- int askNumber(string question, int high, int low)
- {
- int number;
- do
- {
- cout << question << " (" << low << " - " << high << "): ";
- cin >> number;
- } while (number > high || number < low);
-
- return number;
- }
-
- char humanPiece()
- {
- char go_first = askYesNo("Do you require the first move?");
- if (go_first == 'y')
- {
- cout << "\nThen take the first move. You will need it.\n";
- return X;
- }
- else
- {
- cout << "\nYour bravery will be your undoing... I will go first.\n";
- return O;
- }
- }
-
- char opponent(char piece)
- {
- if (piece == X)
- {
- return O;
- }
- else
- {
- return X;
- }
- }
-
- void displayBoard(const vector<char>& board)
- {
- cout << "\n\t" << board[0] << " | " << board[1] << " | " << board[2];
- cout << "\n\t" << "---------";
- cout << "\n\t" << board[3] << " | " << board[4] << " | " << board[5];
- cout << "\n\t" << "---------";
- cout << "\n\t" << board[6] << " | " << board[7] << " | " << board[8];
- cout << "\n\n";
- }
-
- char winner(const vector<char>& board)
- {
-
- const int WINNING_ROWS[8][3] = { {0, 1, 2},
- {3, 4, 5},
- {6, 7, 8},
- {0, 3, 6},
- {1, 4, 7},
- {2, 5, 8},
- {0, 4, 8},
- {2, 4, 6} };
- const int TOTAL_ROWS = 8;
-
-
-
- for(int row = 0; row < TOTAL_ROWS; ++row)
- {
- if ( (board[WINNING_ROWS[row][0]] != EMPTY) &&
- (board[WINNING_ROWS[row][0]] == board[WINNING_ROWS[row][1]]) &&
- (board[WINNING_ROWS[row][1]] == board[WINNING_ROWS[row][2]]) )
- {
- return board[WINNING_ROWS[row][0]];
- }
- }
-
-
- if (count(board.begin(), board.end(), EMPTY) == 0)
- return TIE;
-
-
- return NO_ONE;
- }
-
- inline bool isLegal(int move, const vector<char>& board)
- {
- return (board[move] == EMPTY);
- }
-
- int humanMove(const vector<char>& board, char human)
- {
- int move = askNumber("Where will you move?", (board.size() - 1));
- while (!isLegal(move, board))
- {
- cout << "\nThat square is already occupied, foolish human.\n";
- move = askNumber("Where will you move?", (board.size() - 1));
- }
- cout << "Fine...\n";
-
- return move;
- }
-
- int computerMove(vector<char> board, char computer)
- {
- unsigned int move = 0;
- bool found = false;
-
-
- while (!found && move < board.size())
- {
- if (isLegal(move, board))
- {
-
- board[move] = computer;
-
- found = winner(board) == computer;
-
- board[move] = EMPTY;
- }
-
- if (!found)
- {
- ++move;
- }
- }
-
-
- if (!found)
- {
- move = 0;
- char human = opponent(computer);
-
- while (!found && move < board.size())
- {
- if (isLegal(move, board))
- {
-
- board[move] = human;
-
- found = winner(board) == human;
-
- board[move] = EMPTY;
- }
-
- if (!found)
- {
- ++move;
- }
- }
- }
-
-
- if (!found)
- {
- move = 0;
- unsigned int i = 0;
-
- const int BEST_MOVES[] = {4, 0, 2, 6, 8, 1, 3, 5, 7};
-
- while (!found && i < board.size())
- {
- move = BEST_MOVES[i];
- if (isLegal(move, board))
- {
- found = true;
- }
-
- ++i;
- }
- }
-
- cout << "I shall take square number " << move << endl;
- return move;
- }
-
- void announceWinner(char winner, char computer, char human)
- {
- if (winner == computer)
- {
- cout << winner << "'s won!\n";
- cout << "As I predicted, human, I am triumphant once more -- proof\n";
- cout << "that computers are superior to humans in all regards.\n";
- }
-
- else if (winner == human)
- {
- cout << winner << "'s won!\n";
- cout << "No, no! It cannot be! Somehow you tricked me, human.\n";
- cout << "But never again! I, the computer, so swear it!\n";
- }
-
- else
- {
- cout << "It's a tie.\n";
- cout << "You were most lucky, human, and somehow managed to tie me.\n";
- cout << "Celebrate... for this is the best you will ever achieve.\n";
- }
- }
这个游戏还是需要逻辑的,建议多写这样的游戏锻炼思维。(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)指针简单举例
- 1
- 2
- 3 #include <iostream>
- 4 #include <string>
- 5 using namespace std;
- 6
- 7 int main()
- 8 {
- 9 int *pScore = 0;
- 10 int score = 1000;
- 11
- 12 pScore = &score;
- 13 cout << "Assigning &score to pScore\n";
- 14 cout << "&score is: " << &score << "\n";
- 15 cout << "pScore is: " << pScore << endl;
- 16 cout << "score is: " << score << endl;
- 17 cout << "*pScore is: " << pScore << endl;
- 18 cout << "Adding 500 to score\n";
- 19 score += 500;
- 20 cout << "score is: " << score << endl;
- 21 cout << "*pScore is: " << *pScore << endl;
- 22 cout << "Adding 500 to *pScore\n";
- 23 *pScore += 500;
- 24 cout << "score is: " << score << endl;
- 25 cout << "*pScore is: " << *pScore << endl;
- 26 cout << "Assigning &newScore to pScore" << endl;
- 27 int newScore = 5000;
- 28 pScore = &newScore;
- 29 cout << "&newScore is: " << &newScore << endl;
- 30 cout << "pScore is: " << pScore << endl;
- 31 cout << "newScore is; " << newScore << endl;
- 32 cout << "pScore is: " << *pScore << endl;
- 33 cout << "Assigning &str to pStr" << endl;
- 34 string str = "score";
- 35 string *pStr = &str;
- 36 cout << "str is: " << str << endl;
- 37 cout << "*pStr is: " << *pStr << endl;
- 38 cout << "(*pStr).size() is: " << (*pStr).size() << endl;
- 39 cout << "pStr->size() is: " << pStr->size() << endl;
- 40 return 0;
- 41 }
wang@wang:~/test$ ./pointing Assigning &score to pScore&score is: 0x7ffffba2df58pScore is: 0x7ffffba2df58score is: 1000*pScore is: 0x7ffffba2df58Adding 500 to scorescore is: 1500*pScore is: 1500Adding 500 to *pScorescore is: 2000*pScore is: 2000Assigning &newScore to pScore&newScore is: 0x7ffffba2df5cpScore is: 0x7ffffba2df5cnewScore is; 5000pScore is: 5000Assigning &str to pStrstr is: score*pStr is: score(*pStr).size() is: 5pStr->size() is: 5(067) const pointerint 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) 传递参数举例
- 1
- 2
- 3 #include <iostream>
- 4 using namespace std;
- 5 void badSwap(int x, int y);
- 6 void goodSwap(int *const pX, int *const pY);
- 7 int main()
- 8 {
- 9 int myScore = 150;
- 10 int yourScore = 1000;
- 11 cout << "Original values\n";
- 12 cout << "myScore: " << myScore << endl;
- 13 cout << "yourScore: " << yourScore << endl;
- 14 cout << "Calling basSwap()\n";
- 15 badSwap(myScore, yourScore);
- 16 cout << "myScore: " << myScore << endl;
- 17 cout << "yourScore: " << yourScore << endl;
- 18 goodSwap(&myScore, &yourScore);
- 19 cout << "myScore: " << myScore << endl;
- 20 cout << "yourScore: " << yourScore << endl;
- 21 return 0;
- 22 }
- 23
- 24 void badSwap(int x, int y) {
- 25 int temp;
- 26 temp = x;
- 27 x = y;
- 28 y = temp;
- 29 }
- 30
- 31 void goodSwap(int *const pX, int *const pY) {
- 32 int temp;
- 33 temp = *pX;
- 34 *pX = *pY;
- 35 *pY = temp;
- 36 }
wang@wang:~/test$ ./swap_pointer_ver Original valuesmyScore: 150yourScore: 1000Calling basSwap()myScore: 150yourScore: 1000myScore: 1000yourScore: 150(070) 返回指针- 1
- 2
- 3 #include <iostream>
- 4 #include <string>
- 5 #include <vector>
- 6 using namespace std;
- 7
- 8 string *ptrToElement(vector<string> *const pVec, int i);
- 9
- 10 int main()
- 11 {
- 12 vector<string> inventory;
- 13 inventory.push_back("sword");
- 14 inventory.push_back("armor");
- 15 inventory.push_back("shield");
- 16
- 17 cout << "Sending the object pointed to by returned pointer to cout:\n";
- 18 cout << *(ptrToElement(&inventory, 0)) << endl;
- 19 cout << "Assigning the returned pointer to another pointer.\n";
- 20 string *pStr = ptrToElement(&inventory, 1);
- 21 cout << "Sending the object pointed to by new pointer to cout: \n";
- 22 cout << *pStr << endl;
- 23 cout << "Assigning object pointed to by pointer to a string object.\n";
- 24 string str = *(ptrToElement(&inventory, 2));
- 25 cout << "Sending the new string object to cout:\n";
- 26 cout << str << endl;
- 27 cout << "Altering an object through a returned pointer.\n";
- 28 *pStr = "Healing potion";
- 29 cout << "Sending the altered object to cout:\n";
- 30 cout << inventory[1] << endl;
- 31 return 0;
- 32 }
- 33 string *ptrToElement(vector<string> *const pVec, int i) {
- 34
- 35 return &((*pVec)[i]);
- 36 }
wang@wang:~/test$ ./inventory_pointer Sending the object pointed to by returned pointer to cout:swordAssigning the returned pointer to another pointer.Sending the object pointed to by new pointer to cout: armorAssigning object pointed to by pointer to a string object.Sending the new string object to cout:shieldAltering an object through a returned pointer.Sending the altered object to cout:Healing potion(071) 指针和数组的关系
- 1
- 2
- 3 #include <iostream>
- 4 using namespace std;
- 5 void increase(int *const array, const int NUM_ELEMENTS);
- 6 void display(const int *const array, const int NUM_ELEMENTS);
- 7
- 8 int main()
- 9 {
- 10 cout << "Creating an array of high scores.\n";
- 11 const int NUM_SCORES = 3;
- 12 int highScores[NUM_SCORES] = {3000, 5000, 7000};
- 13 cout << "Displaying scores using array name as a constant pointer.\n";
- 14 cout << *highScores << endl;
- 15 cout << *(highScores + 1) << endl;
- 16 cout << *(highScores + 2) << endl;
- 17
- 18 cout << "Increasing scores by passing array as a constant pointer.\n";
- 19 increase(highScores, NUM_SCORES);
- 20 cout << "Displaying scores by passing array as a constant pointer to a constant.\n";
- 21 display(highScores, NUM_SCORES);
- 22 return 0;
- 23 }
- 24
- 25 void increase(int *const array, const int NUM_ELEMENTS) {
- 26 for (int i = 0; i < NUM_ELEMENTS; i++) {
- 27 array[i] += 50;
- 28 }
- 29 }
- 30
- 31 void display(const int * const array, const int NUM_ELEMENTS) {
- 32 for (int i = 0; i < NUM_ELEMENTS; ++i) {
- 33 cout << array[i] << endl;
- 34 }
- 35 }
wang@wang:~/test$ ./array_passer Creating an array of high scores.Displaying scores using array name as a constant pointer.300050007000Increasing scores by passing array as a constant pointer.Displaying scores by passing array as a constant pointer to a constant.305050507050(072) Programmers often prefix pointer variable names with the letter "p" to remind them that the variable is indeed a pointer.(073) 习题
1. 用指针访问字符串
- 1 #include <iostream>
- 2 #include <string>
- 3 using namespace std;
- 4
- 5 int main()
- 6 {
- 7 string str = "hello world";
- 8 string *pStr = &str;
- 9 cout << "size: " << (*pStr).size() << endl;
- 10 return 0;
- 11 }
wang@wang:~/test$ ./pstr size: 112. 就是把全部引用换成字符串,传入时记得加上&字符。
3. 三个地址是一样的,记得取地址,是去取变量的地址,实在是有点想不通啊。
- 1 #include <iostream>
- 2 using namespace std;
- 3
- 4 int main()
- 5 {
- 6 int a = 10;
- 7 int &b = a;
- 8 int *c = &b;
- 9 cout << &a << endl;
- 10 cout << &b << endl;
- 11 cout << b << endl;
- 12 cout << &(*c) << endl;
- 13 return 0;
- 14 }
wang@wang:~/te./addr0x7fff91aadb2c0x7fff91aadb2c100x7fff91aadb2c
Chapter 8: Classes: Critter Caretaker
(074)类的简单举例
- 1
- 2
- 3 #include <iostream>
- 4 using namespace std;
- 5
- 6 class Critter {
- 7 public:
- 8 int mHunger;
- 9 void greet();
- 10 };
- 11
- 12 void Critter::greet() {
- 13 cout << "Hi. I'm a critter. My hunger level is " << mHunger << ".\n";
- 14 }
- 15
- 16 int main() {
- 17 Critter crit1;
- 18 Critter crit2;
- 19 crit1.mHunger = 9;
- 20 cout << "crit1's hunger level is " << crit1.mHunger << ".\n";
- 21 crit2.mHunger = 3;
- 22 cout << "crit2's hunger level is " << crit2.mHunger << ".\n";
- 23 crit1.greet();
- 24 crit2.greet();
- 25 return 0;
- 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) 增加函数构造器- 1
- 2
- 3 #include <iostream>
- 4 using namespace std;
- 5 class Critter {
- 6 public:
- 7 int m_Hunger;
- 8 Critter(int hunger = 0);
- 9 void greet();
- 10 };
- 11 Critter::Critter(int hunger) {
- 12 cout << "A new critter has been born!" << endl;
- 13 m_Hunger = hunger;
- 14 }
- 15 void Critter::greet() {
- 16 cout << "Hi. I'm a critter. My hunger level is " << m_Hunger << ".\n";
- 17 }
- 18
- 19 int main()
- 20 {
- 21 Critter crit(7);
- 22 crit.greet();
- 23 return 0;
- 24 }
wang@wang:~/test$ ./constructor_critter A new critter has been born!Hi. I'm a critter. My hunger level is 7.
(076)对象综合举例
wang@wang:~/workspace/beginc++game$ ./critter I'm a critter and I feel happy.Criitter Caretakeer0 - Quit1 - Listen to your critter2 - Feed your critter3 - Play with your critterChoice: 1I'm a critter and I feel happy.Criitter Caretakeer0 - Quit1 - Listen to your critter2 - Feed your critter3 - Play with your critterChoice: 2Brruppp.Criitter Caretakeer0 - Quit1 - Listen to your critter2 - Feed your critter3 - Play with your critterChoice: 0Good-bye.(077)习题1
1. 展示对象的变量
- inline void Critter::list() const
- {
- cout << "Hunger: " << m_Hunger << endl;
- cout << "Boredom: " << m_Boredom << endl;
- }
2. 看不懂什么意思。3.变量没有初始化。
Chapter 9: Advanced Classes And Dynamic Memory: Game Lobby
(078) 组合举例
- // Critter Farm
- // Demonstrates object containment
- #include <iostream>
- #include <string>
- #include <vector>
- using namespace std;
-
- class Critter {
- public:
- Critter(const string &name = "");
- string getName() const;
- private:
- string m_Name;
- };
-
- class Farm {
- public:
- Farm(int spaces = 1);
- void add(const Critter &aCritter);
- void rollCall() const;
- private:
- vector<Critter> m_Critters;
- };
-
- int main(int argc, char *argv[])
- {
- Critter crit("Poochie");
- cout << "My critter's name is " << crit.getName() << endl;
- cout << "Creating critter farm.\n";
- Farm myFarm(3);
- cout << "Adding three critters to the farm.\n";
- myFarm.add(Critter("Moe"));
- myFarm.add(Critter("Larry"));
- myFarm.add(Critter("Curly"));
- cout << "Calling Roll...\n";
- myFarm.rollCall();
- return 0;
- }
-
- Critter::Critter(const string &name) : m_Name(name)
- {
-
- }
-
- inline string Critter::getName() const
- {
- return m_Name;
- }
-
- Farm::Farm(int spaces)
- {
- m_Critters.reserve(spaces);
- }
-
- void Farm::add(const Critter &aCritter)
- {
- m_Critters.push_back(aCritter);
- }
-
- void Farm::rollCall() const
- {
- for (vector<Critter>::const_iterator iter = m_Critters.begin(); iter != m_Critters.end(); ++iter)
- cout <<iter->getName() << " here.\n";
- }
My critter's name is Poochie
Creating critter farm.
Adding three critters to the farm.
Calling Roll...
Moe here.
Larry here.
Curly here.
(079) 友元与重载函数- // Friend Critter
- // Demonstrates friend functions and operator overloading
- #include <iostream>
- #include <string>
- using namespace std;
-
- class Critter {
- // make following global functions friends of the Critter class
- friend void peek(const Critter &aCritter);
- friend ostream& operator <<(ostream &os, const Critter& aCritter);
- public:
- Critter(const string &name = "");
- private:
- string m_Name;
- };
- Critter::Critter(const string &name) : m_Name(name) {}
- void peek(const Critter &aCritter);
- ostream &operator <<(ostream & os, const Critter &aCritter);
-
- int main(int argc, char *argv[])
- {
- Critter crit("Poochie");
- cout << "Calling peek() to access crit's private data member, m_Name: \n";
- peek(crit);
- cout << "Sending crit object to cout with the << operator:\n";
- cout << crit;
- return 0;
- }
- // global friend function that can access all of a Critter object's members
- void peek(const Critter &aCritter)
- {
- cout << aCritter.m_Name << endl;
- }
- // overloads the << operator so you can send a Critter object to cout
- ostream &operator <<(ostream &os, const Critter &aCritter)
- {
- os << "Critter Object - ";
- os << "m_Name: " << aCritter.m_Name;
- cout << endl;
- return os;
- }
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.
- // Heap
- // Demonstrates dynamically allocating memory
-
- #include <iostream>
- using namespace std;
- int* intOnHeap()
- {
- int *pTemp = new int(20);
- return pTemp;
- }
- void leak1()
- {
- int *drip1 = new int(30);
- }
- void leak2()
- {
- int *drip2 = new int(50);
- drip2 = new int(100);
- delete drip2;
- }
-
- int main(int argc, char *argv[])
- {
- int *pHeap = new int;
- *pHeap = 10;
- cout << "*pHeap: " << *pHeap << "\n";
- int *pHeap2 = intOnHeap();
- cout << "*pHeap2: " << *pHeap2 << "\n";
- cout << "Freeing memory pointed to by pHeap.\n";
- delete pHeap;
- cout << "Freeig memory pointed to by pHeap2.\n";
- delete pHeap2;
- // get rid of danling pointers
- pHeap = 0;
- pHeap2 = 0;
- return 0;
- }
*pHeap: 10
*pHeap2: 20
Freeing memory pointed to by pHeap.
Freeig memory pointed to by pHeap2.
(081)带有指针的成员变量计算
-
-
- #include <iostream>
- #include <string>
- using namespace std;
-
- class Critter {
- public:
- Critter(const string& name = "", int age = 0);
- ~Critter();
-
- Critter(const Critter &c);
-
- Critter & operator=(const Critter& c);
- void greet() const;
- private:
- string *m_pName;
- int m_Age;
- };
-
- void testDestructor()
- {
- Critter toDestory("Rover", 3);
- toDestory.greet();
- }
- void testCopyConstructor(Critter aCopy)
- {
- aCopy.greet();
- }
- void testAssignmentOp()
- {
- Critter crit1("crit1", 7);
- Critter crit2("crit2", 9);
- crit1 = crit2;
- crit1.greet();
- crit2.greet();
- Critter crit3("crit", 11);
- crit3 = crit3;
- crit3.greet();
- }
- int main(int argc, char *argv[])
- {
- testDestructor();
- Critter crit("Poochie", 5);
- crit.greet();
- testCopyConstructor(crit);
- crit.greet();
- testAssignmentOp();
- return 0;
- }
-
- Critter::Critter(const string &name, int age)
- {
- cout << "Constructor called\n";
- m_pName = new string(name);
- m_Age = age;
- }
-
- Critter::~Critter()
- {
- cout << "Destructor called\n";
- delete m_pName;
- }
-
- Critter::Critter(const Critter &c)
- {
- cout << "Copy Constructor called\n";
- m_pName = new string(*(c.m_pName));
- m_Age = c.m_Age;
- }
-
- Critter &Critter::operator=(const Critter &c)
- {
- cout << "Overload Assignment Operator called\n";
- if (this != &c) {
- delete m_pName;
- m_pName = new string(*(c.m_pName));
- m_Age = c.m_Age;
- }
- return *this;
- }
-
- void Critter::greet() const
- {
- cout << "I'm " << *m_pName << " and I'm " << m_Age << " years old. ";
- cout << "&m_pName: " << &m_pName << endl;
- }
Constructor calledI'm Rover and I'm 3 years old. &m_pName: 0x7ffc9676e280Destructor calledConstructor calledI'm Poochie and I'm 5 years old. &m_pName: 0x7ffc9676e2d0Copy Constructor calledI'm Poochie and I'm 5 years old. &m_pName: 0x7ffc9676e2e0Destructor calledI'm Poochie and I'm 5 years old. &m_pName: 0x7ffc9676e2d0Constructor calledConstructor calledOverload Assignment Operator calledI'm crit2 and I'm 9 years old. &m_pName: 0x7ffc9676e260I'm crit2 and I'm 9 years old. &m_pName: 0x7ffc9676e270Constructor calledOverload Assignment Operator calledI'm crit and I'm 11 years old. &m_pName: 0x7ffc9676e280Destructor calledDestructor calledDestructor calledDestructor 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)本章综合举例
GAME LOBBY0 - Exit the program.1 - Add a player to the lobby.2 - Remove a player from the lobby.3 - Clear the lobby.Enter choice: 1Please enter the name of the new player: wangGAME LOBBY0 - Exit the program.1 - Add a player to the lobby.2 - Remove a player from the lobby.3 - Clear the lobby.Enter choice: 2GAME LOBBY0 - Exit the program.1 - Add a player to the lobby.2 - Remove a player from the lobby.3 - Clear the lobby.Enter choice: 0Good-bye.(086) 习题1. 增加一个<<重载
- ostream &operator<<(ostream &os, const Player &aPlayer)
- {
- os << aPlayer.getName();
- }
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) 简单的继承举例
-
-
- #include <iostream>
-
- using namespace std;
-
- class Enemy {
- public:
- int m_Damage;
- Enemy();
- void attack() const;
- };
-
-
-
- Enemy::Enemy() : m_Damage(10)
- {
-
- }
-
- void Enemy::attack() const
- {
- cout << "Attack inflicts " << m_Damage << " damage points!\n";
- }
-
- class Boss : public Enemy {
- public:
- int m_DamageMultiplier;
- Boss();
- void specialAttack() const;
- };
-
- Boss::Boss() : m_DamageMultiplier(3)
- {
-
- }
-
- void Boss::specialAttack() const
- {
- cout << "Special Attack inflicts " << (m_DamageMultiplier * m_Damage) << " damage points!\n";
- }
-
- int main(int argc, char *argv[])
- {
- cout << "Creating an enemy.\n";
- Enemy enemy1;
- enemy1.attack();
- cout << "Creating a boss.\n";
- Boss boss1;
- boss1.attack();
- boss1.specialAttack();
- return 0;
- }
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)重写父类
-
-
- #include <iostream>
- using namespace std;
- class Enemy {
- public:
- Enemy(int damage = 10);
- void virtual taunt() const;
- void virtual attack() const;
- private:
- int m_Damage;
- };
- class Boss : public Enemy {
- public:
- Boss(int damage = 30);
- void virtual taunt() const;
- void virtual attack() const;
- };
-
- int main(int argc, char *argv[])
- {
- cout << "Enemy object:\n";
- Enemy anEnemy;
- anEnemy.taunt();
- anEnemy.attack();
- cout << "Boss object:\n";
- Boss aBoss;
- aBoss.taunt();
- aBoss.attack();
- return 0;
- }
-
- Enemy::Enemy(int damage) : m_Damage(damage)
- {
-
- }
-
- void Enemy::taunt() const
- {
- cout << "The enemy says he will fight you.\n";
- }
-
- void Enemy::attack() const
- {
- cout << "Attack! Inflicts " << m_Damage << " damage points.\n";
- }
-
- Boss::Boss(int damage) : Enemy(damage)
- {
-
- }
-
- void Boss::taunt() const
- {
- cout << "The boss says he will end your pitiful existence.\n";
- }
-
- void Boss::attack() const
- {
- Enemy::attack();
- cout << "And laught heartily at you.\n";
- }
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) 多态举例
-
-
- #include <iostream>
- using namespace std;
- class Enemy {
- public:
- Enemy(int damage = 10);
- virtual ~Enemy();
- void virtual attack() const;
- protected:
- int *m_pDamage;
- };
- class Boss : public Enemy {
- public:
- Boss(int multiplier = 3);
- virtual ~Boss();
- void virtual attack() const;
- protected:
- int *m_pMultiplier;
- };
-
- int main(int argc, char *argv[])
- {
- cout << "Calling attack() on boss object through pointer to enemy:\n";
- Enemy *pBadGuy = new Boss();
- pBadGuy->attack();
- cout << "Deleting pointer to Enemy:\n";
- delete pBadGuy;
- pBadGuy = 0;
- return 0;
- }
-
- Enemy::Enemy(int damage)
- {
- m_pDamage = new int(damage);
- }
-
- Enemy::~Enemy()
- {
- cout << "In enemy destructor, deleting m_pDamage.\n";
- delete m_pDamage;
- m_pDamage = 0;
- }
-
- void Enemy::attack() const
- {
- cout << "An enemy attacks and inflicts " << *m_pDamage << " damage points.\n";
- }
-
- Boss::Boss(int multiplier)
- {
- m_pMultiplier = new int(multiplier);
- }
-
- Boss::~Boss()
- {
- cout << "In boss destrcutor, deleting m_pMultiplier.\n";
- delete m_pMultiplier;
- m_pMultiplier = 0;
- }
-
- void Boss::attack() const
- {
- cout << "A boss attacks and inflicts " << (*m_pDamage) * (*m_pMultiplier) << " damage points.\n";
- }
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)抽象类-
-
- #include <iostream>
- using namespace std;
- class Creature {
- public:
- Creature(int health = 100);
-
- virtual void greet() const = 0;
- virtual void displayHealth() const;
- protected:
- int m_Health;
- };
- class Orc : public Creature {
- public:
- Orc(int health = 120);
- virtual void greet() const;
- };
-
- int main(int argc, char *argv[])
- {
- Creature *pCreature = new Orc();
- pCreature->greet();
- pCreature->displayHealth();
- return 0;
- }
-
- Creature::Creature(int health) : m_Health(health)
- {
-
- }
-
- void Creature::displayHealth() const
- {
- cout << "Health: " << m_Health << endl;
- }
-
- Orc::Orc(int health) : Creature(health)
- {
-
- }
-
- void Orc::greet() const
- {
- cout << "The orc grunts hello.\n";
- }
The orc grunts hello.Health: 120096. 纯虚函数
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类
- class FinalBoss : public Boss {
- public:
- FinalBoss();
- void MegaAttack();
- };
2. 第二个不会。这本书很基础,但是有两个例子不错。
总的来说是快速熟悉C++,并不是教具体的语法等知识点。
更多地来源于自己的编程总结。
转载来源:http://blog.csdn.net/wan_exe/article/details/61930540