关于指针和取消引用

On Pointers and Dereferencing

本文关键字:取消 引用 指针 于指针      更新时间:2023-10-16

我最近一直在学习C++,并拿起了《C++通过游戏编程》一书。我在Pointers一章中,有人给我举了一个我有问题的例子。代码是这样的:

#include "stdafx.h"
#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 valuesn";
    cout << "myScore: " << myScore << "n";
    cout << "yourScore: " << yourScore << "nn";
    cout << "Calling badSwap()n";
    badSwap(myScore, yourScore);
    cout << "myScore: " << myScore << "n";
    cout << "yourScore: " << yourScore << "nn";
    cout << "Calling goodSwap()n";
    goodSwap(&myScore, &yourScore);
    cout << "myScore: " << myScore << "n";
    cout << "yourScore: " << yourScore << "n";
    cin >> myScore;
    return 0;
}
void badSwap(int x, int y)
{
    int temp = x;
    x = y;
    y = temp;
}
void goodSwap(int* const pX, int* const pY)
{
    //store value pointed to by pX in temp
    int temp = *pX;
    //store value pointed to by pY in address pointed to by pX
    *pX = *pY;
    //store value originally pointed to by pX in address pointed to by pY
    *pY = temp;
}

在goodSwap()函数中有一行:

*pX = *pY;

你为什么要取消对任务双方的引用?这难道不等于说"1000=150"吗?

你为什么要取消对任务双方的引用?这难道不等于说"1000=150"吗?

不,就像下面一样:

int x = 1000;
int y = 150;
x = y;

不等于说"1000=150"。您正在分配给对象,而不是它当前包含的值。

以下内容完全相同(因为表达式*px是指对象x的左值,表达式*py是指对象y的左值;它们实际上是别名,而不是对象数值的某种奇怪的、断开连接的版本):

int   x = 1000;
int   y = 150;
int* px = &x;
int* py = &y;
*px = *py;

*px=*py表示我们分配的值不是地址,而是从py的地址到px的地址。

跳过本书的章节或购买另一章:现在在C++中不需要使用纯指针。

还有一个std::swap函数,它执行C++isch的操作。