这是一个菜鸟问题,但我不确定如何在 C++ 中通过引用传递。我有以下设置节点和一些功能的类。
class Node
{
public:
Node *next;
int data;
Node(int dat)
{
next = NULL;
data = dat;
}
Node* getNext()
{ return next; }
void setNext(Node *n)
{ next = n;}
void reverse(Node *root)
{
Node *previous = NULL;
while(root != NULL)
{
Node *next = root->getNext();
root->setNext(previous);
previous = root;
root = next;
}
root = previous;
}
};
现在,我的小类(class)的目的是创建一个单向链表并具有反转它的能力。如果我在反向结束时返回名为“previous”的节点,它似乎工作正常。
但是看看我的主要功能:
int main()
{
Node *root = new Node(1);
Node *num2 = new Node(2);
Node *num3 = new Node(3);
Node *num4 = new Node(4);
root->setNext(num2);
num2->setNext(num3);
num3->setNext(num4);
root->printList();
root->reverse(root);
root->printList();
return 0;
}
printList() 出于空间原因被省略,但它只打印给定节点的列表。问题是,当调用 root->reverse(root) 时,root 实际上并没有指向“previous”。
输出是这样的:
1
2
3
4
// the value of previous from the reverse function is 4
1
我真的不明白输出。有人愿意解释发生了什么吗? (为什么列表没有反转,即使我做了类似 root = root->reverse(root) 的事情,其中 reverse 返回前一个,它会)为什么 root 现在只指向它自己?我是 C++ 的新手,感谢您的帮助!
最佳答案
C++ 支持引用语义。因此,对于给定的函数:
void foo(Bar& bar);
要通过引用传递,您需要:
int main() {
Bar whatsit;
foo(whatsit);
return 0;
}
就是这样!
这通常与传递指针混淆,对于函数,例如:
void foo(Bar* bar);
你会这样做:
int main() {
Bar whatisit;
foo(&whatsit);
return 0;
}
区别主要是语义问题: - 引用总是有效的。没有理由检查 NULL 指针。 - 指针可能为 NULL,因此应进行检查。
但是,如果程序员决定作恶并滥用引用语义,则引用有可能引用 NULL 指针,但原则仍然存在。
关于c++ - 在 C++ 中通过引用传递对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3877856/