将链表传递给函数并确保它未被修改
Passing a linked list to a function and making sure it is not modified
有没有办法将链表传递给函数并确保它不会被修改?
我们可以将 const head 指针传递给函数,这将确保头部不会被修改。但是,该函数可以从 head 访问其他节点并修改这些节点。
可能你想尝试这样的事情:
class Node{
private:
Node* _next;
public:
Node(Node* next) : _next(next){}
Node* getNext(){ return _next; }
const Node* getNext() const {return _next; }
};
附言恕我直言。C++ proramers 经常忽略引用并在不需要的地方使用指针。这可能是您情况的一种选择吗?:)
struct Node{ Node& _next; Node(Node& next) : _next(next){} };
PP.SS。在您的具体情况中,可能不需要第二个getNext。这只是为了让生活更轻松,如果你有函数接受 const 节点指针。在下面的示例中,我将尝试使用const方法进一步清除这个想法:
#include <iostream>
#include <cstdlib>
class Node{
private:
Node* _next;
public:
Node(Node* next) : _next(next){}
Node* getNext(){ std::cout << "getNextn"; return _next; }
const Node * getNext() const { std::cout << "getNext constn"; 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);
}
如果你想遍历linkedList而不改变它, 只需用常量函数重载遍历函数即可。
相关文章:
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何确保C++函数在定义之前声明(如override关键字)
- 独立读取-修改-写入顺序
- 当系统的卷被修改时,如何修改WASAPI环回捕获卷
- 修改函数中的指针(将另一个指针作为参数传递)
- 为什么我可以通过引用修改常量返回
- 对于结构,表达式必须是可修改的ivalue
- QML:修改在不同QML文件(而非main.QML)中定义的子对象的属性
- 如何确保在使用基于布尔值的两个方法之一调用方法时避免分支预测错误
- 为什么不能修改对象中的值?另外,我如何改进此链表?
- 修改创建帐户程序
- 使用Unique_ptr确保工厂中的对象唯一
- 我应该如何修改此代码以使用给定字符串中的字母打印菱形图案
- 如何从子成员函数修改父公共成员变量
- 修改 VS Code 中的默认C++代码段
- 将链表传递给函数并确保它未被修改
- 是否要确保一个线程修改的任何数据类型的共享变量对其他线程可见
- 我如何确保修改.H文件时,使用Visual Studio 2008将包括其在内的.cc文件自动编译
- 如何确保作为模板参数传递的函数类型不会修改参数
- C++ 如何确保复制构造函数不会修改原始对象的指针数据成员?