《C++游戏编程入门》第7章 指针:Tic-Tac-Toe 2.0
7.1 指针基础
包含内存地址的变量。
07.pointing.cpp
#include <iostream>
#include <string>
using namespace std;
int main()
{
int *pAPointer; // 声明指针
int *pScore = nullptr; // 声明并初始化指针,空指针
int score = 1000;
pScore = &score; // 地址赋值给指针
cout << "Assigning &score to pScore\n";
cout << "&score is: " << &score << "\n"; // address of score variable
cout << "pScore is: " << pScore << "\n"; // address stored in pointer
cout << "score is: " << score << "\n";
cout << "*pScore is: " << *pScore << "\n\n"; // 指针解引用
cout << "Adding 500 to score\n";
score += 500;
cout << "score is: " << score << "\n";
cout << "*pScore is: " << *pScore << "\n\n";
cout << "Adding 500 to *pScore\n";
*pScore += 500;
cout << "score is: " << score << "\n";
cout << "*pScore is: " << *pScore << "\n\n";
cout << "Assigning &newScore to pScore\n";
int newScore = 5000;
pScore = &newScore; // 指针重新赋值
cout << "&newScore is: " << &newScore << "\n";
cout << "pScore is: " << pScore << "\n";
cout << "newScore is: " << newScore << "\n";
cout << "*pScore is: " << *pScore << "\n\n";
cout << "Assigning &str to pStr\n";
string str = "score";
string *pStr = &str; // 对象指针
cout << "str is: " << str << "\n";
cout << "*pStr is: " << *pStr << "\n";
cout << "(*pStr).size() is: " << (*pStr).size() << "\n";
cout << "pStr->size() is: " << pStr->size() << "\n";
return 0;
}
7.2 指针和常量
const用来限制指针。
- 常量指针
int score = 100;
int* const pScore = &score;//常量指针,必须声明时初始化,指向地址固定
*pScore = 500;//可修改指向的值
- 指向常量的指针(指针常量)
const int* pNumber;//int const * pNumber;
int one = 1;
pNumber = &one;//可指向常量或非常量,指向的值是常量(无法通过指针修改)
int two = 2;
pNumber = &tow;//指向地址可改变
//*pNumber = 3;//error,指向的值不可改变
- 指向常量的常量指针(常量引用)
int N = 5;
//const int const * pBound = &N;
//声明时初始化,指向地址固定,指向的值固定
//可指向常量或非常量,指向的值是常量(无法通过指针修改)
const int* const pBound = &N;
7.3 传递指针
传址调用。
07.swap_pointer_ver.cpp
#include <iostream>
using namespace std;
void badSwap(int x, int y);
void goodSwap(int *const pX, int *const pY); // 常量指针,指向地址固定,指向的值可修改
int main()
{
int myScore = 150;
int yourScore = 1000;
cout << "Original values\n";
cout << "myScore: " << myScore << "\n";
cout << "yourScore: " << yourScore << "\n\n";
cout << "Calling badSwap()\n";
badSwap(myScore, yourScore);
cout << "myScore: " << myScore << "\n";
cout << "yourScore: " << yourScore << "\n\n";
cout << "Calling goodSwap()\n";
goodSwap(&myScore, &yourScore);
cout << "myScore: " << myScore << "\n";
cout << "yourScore: " << yourScore << "\n";
return 0;
}
void badSwap(int x, int y)
{
int temp = x;
x = y;
y = temp;
}
void goodSwap(int