首页 > 解决方案 > 试图学习指针,为什么要使用它们而不是 &?

问题描述

我正试图围绕 C++ 中的指针转转,使用指针与仅使用 &variable 在该位置获取对象有什么意义?

例如(没有实际运行此代码,仅作为示例):

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++c++11pointers

解决方案


指针还可以帮助您避免切片问题。例如,如果您有许多从同一个父类派生的不同类,并且您想将它们放入数据类型父列表中

#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不是指针,则所有唯一的数据Child1Child2被切断,并且这两个实例都将成为类的实例Parent


推荐阅读