C :功能获取指针或引用

C++ : function gets pointer or refernce

本文关键字:引用 指针 获取 功能      更新时间:2023-10-16

我很不清楚何时会获得指针或参考。

可以说我正在实施BFS。这是我的实现:

// Assuming There is a class Node :
class Node {
    public:
    int val;
    bool visited;
    list<Node*> neighbours;
};
void BFS (Node* root) {
    if(root == NULL) {
        return ;
    }
    queue<Node*> Q;
    Q.push(root);
    while(!Q.empty()){
        Node* temp = Q.front();
        Q.pop();
    for(list<Node*>::iterator it = root->neighbours.begin() ; it != root->neighbours.end() ; it++){
            if((*it)->visited == true) continue;
            Q.push((*it));
            (*it)->visited = true;
        }
        if(!Q.empty()){
            cout << temp->val << ",";
        } else {
            cout << temp->val << endl;
        }
    }
}

我的问题是:函数BFS是否应该获得指针或参考,为什么?

另外,我很乐意听到有关实施ITSLEF的更多评论。

非常感谢!

可能有不同的方法和不同的原因,使指针用作函数参数

  1. 如果您要在BFS函数内部进行指针算术,则应将指针用作参数。
  2. 有时候,检查指针是否为null并根据此操作进行一些操作很有用。

似乎这不是使用指针作为参数的重要原因,但是null可以在其上保存非常重要的信息。例如,有二进制搜索树实现null指针显示节点是叶子。

在您的示例中,您还检查root是否为null并在这种情况下返回。

我建议将其保留为接受指针,以便您检查NULL。

ref vs C 的指针福利

接受指针具有以下行为,并允许null(0)值

int main() {
  ...
  { 
    Graph g;
    ...
    Node x(...);   //x is a reference to a Node on the stack
    g.BFS(&x);     //Notice the need to use '&' to convert to pointer
  }
  {
    Graph g;
    ...
    Node* x = Node(...);   //x is a ("Node") pointer to a Node on the stack
    g.BFS(x);              //passes as a pointer
  }
  { 
    Graph g;
    ...
    Node* x = NULL;
    g.BFS(x)          //works -- is allowed
  }
  {
    Graph g;
    ...
    Node* x = new Node(...);   //x is a ("Node") pointer to a Node on the heap
    g.BFS(x);                  //passes as a pointer
  }
}

接受为参考具有以下行为,不允许null(0)值:

int main() {
  ...
  { 
    Graph g;
    ...
    Node x(...);   //x is a reference to a Node on the stack
    g.BFS(x);     //Pass by reference
  }
  {
    Graph g;
    ...
    Node* x = Node(...);   //x is a ("Node") pointer to a Node on the stack
    g.BFS(*x);              //Notice the need to dereference x to pass by reference
  }
  {
    Graph g;
    ...
    Node* x = new Node(...);   //x is a ("Node") pointer to a Node on the heap
    g.BFS(*x);                  //Notice the need to dereference x to pass by reference
  }
  { 
    Graph g;
    ...
    Node* x = NULL;
    g.BFS(x)   //does not work, can't pass 0 val to function expecting a reference      
  }
}