指向C ++中的指针的指针

路易斯

您好,我是c ++的新手,我试图弄清楚如何使用指针更改同一对象。

例如,如果我有一个指针向量

std::vector<myclass*> top;

并说top [0] = NULL我想使用另一个指针来更改它

myclass* other = top[0];
other = new myclass();

这样,当我访问top [0]时,它将指向创建的新对象吗?对不起,有点混乱,但这就是想法。

一些程序员哥们

例如,如果您有一个向量int

std::vector<int> vec(10);

然后做类似的事情

int other = vec[0];
other = 5;

我想大多数人都会明白,分配other = 5;会改变变量的值other而已,而不是价值vec[0]

现在,让您获取代码:

myclass* other = top[0];
other = new myclass();

这是完全相同的事情:赋值other = new myclass();仅更改变量,other并且变量指向的位置不变top[0]

您想要的是other用作对中值引用top[0],您可以通过使用引用来实现:

myclass*& other = top[0];
other = new myclass();

现在other将引用in中的值top[0],因此分配将更改top[0]

为了完整起见,并与标题中的指针到指针保持一致,您当然可以通过指向指针的指针来解决它:

myclass** other = &top[0];
*other = new myclass();

上面的代码other将指向top[0],您需要在分配中使用解引用运算符*(如中的*other)来更改处的值top[0]我真的推荐参考。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章