试图学习指针,为什么要使用它们而不是仅仅使用&?
Trying to learn pointers, why use them instead of just &?
我正在尝试将头缠绕在C 中的指针中,使用指针vs vs仅使用&变量在该位置将对象获取的意义是什么?
例如(仅出于一个示例,实际上没有运行此代码(:
int score{10};
int *score_ptr {nullptr};
score_ptr = &score;
cout << "Address of score is: " << &score << endl; // why not just this?
cout << "Address of score is: " << score_ptr << endl; // more work for same?
有人想在C
中使用指针的原因很多我认为最基本的一个是与new
结合使用的。例如,这是C 中的未定义行为:
SomeClass* someFunc() {
SomeClass out;
return &out;
}
这是未定义的行为,因为out
在someFunc
内只有一个有效的内存位置,因此任何调用该功能的人都将处理一个不良的SomeClass
实例。处理此操作的正确方法是:
SomeClass* someFunc() {
SomeClass* out = new SomeClass();
return out;
}
另一个原因可能与nullptr
结合使用。例如,说您在程序中有一堆经过精心编码的人,并且正在实施电话目录。运行该程序的用户输入电话号码,如果电话号码不属于任何人,则该程序要么给个人提供指针或nullptr
。您将无法使用 &
另一个原因是管理从公共类继承的扩展类
指针还可以帮助您避免切片问题。例如,如果您从同一父级派生了许多不同的类,并且要将它们放入datatype parent
的列表中#include <vector>
class Parent{
protected:
//variables common to all the children of the parent class
public:
//methods common to all the children classes
}
class Child1: public Parent{
private:
//data unique to this class
public:
//methods unique to this class
}
class Child2: public Parent{
private:
//data unique to this class
public:
//methods unique to this class
}
std::vector<Parent*> listOfInstances;
Child1 instance1;
Child2 instance2;
listOfInstances.push_back(instance1);
listOfInstances.push_back(instance2);
如果向量称为listOfInstances
不是指针,则所有数据是Child1
所唯一的数据,并且Child2
将被切断,并且这两个实例都将成为Parent
&score
是类型"指向int"的序言。prvalue的意思是"纯粹的值可以在作业语句的右侧出现"。
int* score_ptr
是"指向int指针"类型的lvalue。这意味着它可以在作业语句的左侧进行。
区别在于一个是没有身份的 value ,另一个是具有身份的 actiable 。
您不能执行&&score
,但是您可以执行&score_ptr
。您可以分配给score_ptr
,无法分配给&score
。
指针类似于一张纸,上面写着街道地址。价值是街道地址。
指针变量是一个街道地址,有一张纸在其中说街道地址是。
假设您每4个月去搬家一次;也许您是大学的一名学生。给某人您当前的地址浪费时间,因为它将在几个月内垃圾。给他们父母的地址,并让他们将邮件转发给您,这更有意义。
在这里,您生活在int
中。如果您告诉某人您的父母的地址 - int*
类型变量的地址 - 即使您四处走动,他们也可以向您发送东西。
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 为什么在全局范围内使用"extern int a"似乎不行?
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 为什么会发生堆损坏
- 为什么使用 "this" 指针调用派生成员函数?
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 为什么比较运算符如此快速
- 为什么 Serial.println(<char[]>);返回随机字符?
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 试图学习指针,为什么要使用它们而不是仅仅使用&?
- 当我们在C 中已经可以使用STL排序功能时,为什么我们需要学习不同的排序算法
- 学习C :为什么这是非法的
- 当"if else"已经存在时,我为什么要学习"switch case"
- 学习左值和右值,但不确定为什么这个代码有效
- 我正在使用Xcode进行c ++编程和学习。为什么我不能在一个项目中放置许多具有 MAIN 功能的单独源文件?
- 学习指针C++使用以下代码进入核心转储,我真的不知道为什么?
- 为什么我在Microsoft Visual C++2010学习版中收到此消息
- 模板:我需要更好地学习这些?为什么我得到错误