C :功能获取指针或引用
C++ : function gets pointer or refernce
我很不清楚何时会获得指针或参考。
可以说我正在实施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的更多评论。
非常感谢!
可能有不同的方法和不同的原因,使指针用作函数参数
- 如果您要在BFS函数内部进行指针算术,则应将指针用作参数。
- 有时候,检查指针是否为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
}
}
相关文章:
- C++取消引用指针.为什么会发生变化
- 深层复制具有自引用指针的类
- Visual c ++,使用字符串引用/指针调用 dll 函数
- std::unordered_map::提取引用/指针失效
- 为什么在引用指针时将 const 放在 & 符号的左侧有效,而在右侧则无效?
- 区分接受常量参数的函数引用/指针和与函数参数同名的非常量参数
- 如何在 c++ 中使用带有数学运算的引用/指针?
- 了解通过引用传递取消引用指针时C++堆/堆栈分配
- 取消引用指针并立即为其分配变量,导致分段错误
- 如何获取指向类(而不是对象)的引用/指针
- 将类型参数传递给自引用指针
- 我应该如何定义返回指针的函数?(引用指针与指针指针)
- 在析构函数内取消引用指针时出现分段错误
- 来自引用指针的内存泄漏
- 引用指针后面的值
- 无法取消引用指针
- 引用指针调用成员函数
- 未定义的引用指针的变量模板在clang中功能,而不是GCC
- 取消引用指针以创建数组的副本
- 有关启动引用指针的引用的问题