C ++技巧与*和它是什么意思
c++ trick with *& what does it mean?
可能的重复项:
指向引用的指针和指向指针的引用之间的区别
我是C++的新手,我从事一个非常复杂的项目。当我试图弄清楚一些事情时,我看到了一件有趣的事情:
n->insertmeSort((Node *&)first);
当我们深入研究insertmeSort时,我们可以看到相同的内容:
void Node::insertme(Node *&to)
{
if(!to) {
to=this;
return;
}
insertme(value>to->value ? to->right : to->left);
}
所以我问题的原因是:Node *&
- 星号和与号,为了什么?
这看起来很棘手,对我来说很有趣。
它是
对指针的引用。与任何常规引用一样,但基础类型是一个指针。
在引用之前,逐个引用的指针必须使用双指针来完成(一些有C思想的人仍然这样做,我偶尔是其中之一)。
为了避免有任何疑问,请尝试这样做以真正沉浸其中:
#include <iostream>
#include <cstdlib>
void foo (int *& p)
{
std::cout << "&p: " << &p << std::endl;
}
int main(int argc, char *argv[])
{
int *q = NULL;
std::cout << "&q: " << &q << std::endl;
foo(q);
return EXIT_SUCCESS;
}
输出(你的值会不同,但 &p == &q)
&q: 0x7fff5fbff878
&p: 0x7fff5fbff878
希望很清楚,foo()
中的 p
确实是对 main()
中指针q
的引用。
这不是
一个技巧,它只是类型——"引用指向Node
的指针"。
n->insertmeSort((Node *&)first);
调用insertmeSort
,结果是将first
转换为Node*&
。
void Node::insertme(Node *&to)
声明insertme
将指向Node
的指针的引用作为参数。
引用和指针工作原理示例:
int main() {
//Initialise `a` and `b` to 0
int a{};
int b{};
int* pointer{&a}; //Initialise `pointer` with the address of (&) `a`
int& reference{a};//Make `reference` be a reference to `a`
int*& reference_to_pointer{pointer_x};
//Now `a`, `*pointer`, `reference` and `*reference_to_pointer`
//can all be used to manipulate `a`.
//All these do the same thing (assign 10 to `a`):
a = 10;
*pointer = 10;
reference = 10;
*reference_to_pointer = 10;
//`pointer` can be rebound to point to a different thing. This can
//be done directly, or through `reference_to_pointer`.
//These lines both do the same thing (make `pointer` point to `b`):
pointer = &b;
reference_to_pointer = &b;
//Now `b`, `*pointer` and `*reference_to_pointer` can
//all be used to manipulate `b`.
//All these do the same thing (assign 20 to `b`):
b = 20;
*pointer = 20;
*reference_to_pointer = 20;
}
*& 表示您正在通过引用传递指针。 因此,在本例中,您通过引用此函数来传递指向对象的指针。 如果没有引用,此行将不起作用
if(!to) {
to=this;
return;
}
相关文章:
- C++ - "Incomplete type not allowed"错误是什么意思,我该如何修复它?
- 这个语句到底是什么意思 stack<int, list<int> > 它与 stack 有何不同<int>?
- 错误 opencv 错误断言失败 (p [-1] <= 2) 是什么意思以及如何处理它?
- 尾随空格是什么意思,它和空白有什么区别?
- C ++技巧与*和它是什么意思
- 字符串数组[] = " " 是什么;意思是,为什么它有效?
- int main() 的返回值是什么意思,如何显示它?
- 我在运行时遇到以下错误.它是什么意思?我该如何调试它
- VOID NTAPI是什么意思?在哪里可以找到它的参考资料
- constchar***是什么意思?它是如何从C语言转换为Java语言的
- C++模板实例化,它到底是什么意思
- 函数声明中带有[]运算符的指针——它是什么意思
- 这个typedef是什么意思,它有什么好处
- 警告C4309 -它是什么意思,在这种情况下可以忽略它
- auto在c++ 11中的含义改变;请删除它这是什么意思
- in(std::cin):它是什么意思
- 这个基数是什么意思?它是标准的c++关键字吗?
- 错误是什么意思"void-value is not ignored"以及如何删除它?
- Boost编译标志,它是什么意思
- new (nothrow)操作符实际上是什么意思,为什么要使用它