c++ - 试图学习指针,为什么要使用它们而不是 &?
问题描述
我正试图围绕 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?
解决方案
指针还可以帮助您避免切片问题。例如,如果您有许多从同一个父类派生的不同类,并且您想将它们放入数据类型父列表中
#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
推荐阅读
- apache - 在通过 Apache 作为代理加载外部网站时操作 URL
- go - Gorm 多个事务以删除旧的搜索条件
- excel - 使用 Trim 功能删除不需要的多余字符
- docker - Docker容器依赖
- azure-devops - Azure Devops 自定义电子邮件通知
- json - 如何将嵌套的 json 转换为 datafarme
- reactjs - 是否可以将 ag-grid 无限滚动与 react-redux 和钩子一起使用?
- javascript - 如果数字有差距,找到有差距的数字并不正确
- javascript - 使用带有 openlayers 的 javascript 导入
- oracle - 有没有办法从 PL/SQL 中的存储过程执行 robocopy cmd?