是否可以将链接列表传递给函数并确保不对其进行修改?
我们可以将const头指针传递给函数,这将确保不修改头。但是,该功能可以从头访问其他节点并进行修改。
也许您想尝试这样的事情:
class Node{
private:
Node* _next;
public:
Node(Node* next) : _next(next){}
Node* getNext(){ return _next; }
const Node* getNext() const {return _next; }
};
ps.s。恕我直言。 C ++通常会忽略引用,并在不需要的地方使用指针。这可能是您的选择吗? :)
struct Node{ Node& _next; Node(Node& next) : _next(next){} };
PP.SS。在您的具体情况下,可能不需要第二个getNext。如果您具有使用const节点指针的函数,则只是为了简化生活。在下面的示例中,我将尝试通过const-method进一步清除该想法:
#include <iostream>
#include <cstdlib>
class Node{
private:
Node* _next;
public:
Node(Node* next) : _next(next){}
Node* getNext(){ std::cout << "getNext\n"; return _next; }
const Node * getNext() const { std::cout << "getNext const\n"; return _next; }
};
void f1(Node* node){ node->getNext(); }
void f2(const Node* node){ node->getNext(); }
int main() {
Node* n1 = new Node(NULL);
Node* n2 = new Node(n1);
f1(n2);
f2(n2);
}
如果您要遍历链表而不进行更改,只是用遍历函数重载遍历函数。