关于指针和取消引用
On Pointers and Dereferencing
我最近一直在学习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的操作。
相关文章:
- C++取消引用指针.为什么会发生变化
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 取消引用运算符不能重载
- 在他自己的方法中,有可能将一个对象取消引用到另一个对象吗
- C++ 关于指针取消引用的技术问题
- 没有取消引用/解包对象的标准方法?
- 列表 iter 不取消引用 使用列表进行插入排序
- 在这个函数中是有缺陷的,因为取消引用 null 是无效的,所以我想更改代码
- 取消引用结束指针到数组类型的一个
- 取消引用向量时出现问题
- 取消引用指向整数的指针时获得不同的结果
- C++:取消引用十六进制值,有点语法问题
- C/C++ 取消引用错误:在空检查之前取消引用
- 取消引用后C++空测试
- 立即取消引用unique_ptr
- 如何在不使用临时变量的情况下取消引用返回指针的函数的返回值?
- 取消引用 void 指针以将值分配给结构
- boost_multi_index迭代器取消引用给出常量
- 矢量迭代器不能与 std::shared_ptr<> 取消引用
- C++我们可以取消引用此指针吗?如果是这样,那么如何,如果不是,那为什么?