《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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值