我最近一直在努力学习C ++并拿起了“C ++ Through Game Programming”这本书。我正在关于指针的章节,我已经有一个例子,我有一个问题。代码是这样的:
#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 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";
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”吗?
答案 0 :(得分:7)
为什么要取消引用作业的双方?不等于说&#34; 1000 = 150&#34;?
不,如下所示:
int x = 1000;
int y = 150;
x = y;
不等于说&#34; 1000 = 150&#34;。您正在分配对象,而不是它当前包含的值。
以下正好相同(因为表达式*px
是引用对象x
的左值,而表达式*py
是左值引用对象y
;它们实际上是别名,而不是某些奇怪的,断开连接的对象版本和数字值:
int x = 1000;
int y = 150;
int* px = &x;
int* py = &y;
*px = *py;
答案 1 :(得分:0)
* px = * py表示我们从py的地址到px的地址分配值not address。
答案 2 :(得分:-1)
翻阅书中的章节或购买另一本书: 现在不需要在C ++中使用普通指针。
还有一个std::swap函数,用于处理C ++ isch。