《C++游戏编程入门》第6章 引用:Tic-Tac-Toe
6.1 使用引用
引用为变量提供另一个名称,指针的语法糖。
06.referencing.cpp
#include <iostream>
using namespace std;
int main()
{
int myScore = 1000;
int &mikesScore = myScore; // 创建引用,声明时必须初始化
cout << "myScore is: " << myScore << "\n";
cout << "mikesScore is: " << mikesScore << "\n\n"; // 访问被引用的值
cout << "Adding 500 to myScore\n";
myScore += 500;
cout << "myScore is: " << myScore << "\n";
cout << "mikesScore is: " << mikesScore << "\n\n";
cout << "Adding 500 to mikesScore\n";
mikesScore += 500; // 修改被引用的值
cout << "myScore is: " << myScore << "\n";
cout << "mikesScore is: " << mikesScore << "\n\n";
return 0;
}
6.2 通过传递引用改变实参
函数传值时无法改变实参,而引用可以。
06.swap.cpp
#include <iostream>
using namespace std;
void badSwap(int x, int y); // 传值不改变实参
void goodSwap(int &x, int &y); // 传引用可以改变实参
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 &x, int &y)
{
int temp = x;
x = y;
y = temp;
}
6.3 传递引用以提高效率
值传递,复制,额外开销。
引用效率高,不需要实参复制。
06.inventory_displayer.cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// parameter vec is a constant reference to a vector of strings
void display(const vector<string> &inventory); // 常量引用无法修改
int main()
{
vector<string> inventory;
inventory.push_back("sword");
inventory.push_back("armor");
inventory.push_back("shield");
display(inventory);
return 0;
}
// parameter vec is a constant reference to a vector of strings
void display(const vector<string> &vec)
{
cout << "Your items:\n";
for (vector<string>::const_iterator iter = vec