试图学习指针,为什么要使用它们而不是仅仅使用&?

Trying to learn pointers, why use them instead of just &?

本文关键字:为什么 学习 指针      更新时间:2023-10-16

我正在尝试将头缠绕在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;
}

这是未定义的行为,因为outsomeFunc内只有一个有效的内存位置,因此任何调用该功能的人都将处理一个不良的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*类型变量的地址 - 即使您四处走动,他们也可以向您发送东西。