c++ - 如何将常量指针传递给类中的方法

标签 c++ pointers constants

我有一个 Node 类的构造函数:

Node::Node(int item,  Node const * next)
{
    this->item = item;
    this->next = next;
}

当我编译它时出现编译错误:从'const Node*'到'Node*'的无效转换

有没有办法传递指向常量数据的指针?

最佳答案

你做的是正确的,但编译器提示是正确的:你正在将“指向 const Node 的指针”分配给类型为“指向非const 节点”。如果您稍后修改 this->next,您将违反“我不会修改 next 指向的变量。

”的约定。

简单的解决方法就是将 next 声明为指向非常量数据的指针。如果变量 this->nextNode 对象的生命周期内真的永远不会被修改,那么您可以选择将类成员声明为指向 的指针>const 对象:

class Node
{
    ...
    const Node *next;
}:

还要注意“指向const 数据的指针”和“const 指向数据的指针”之间的区别。对于单级指针,指针的const有四种类型:

Node *ptr;  // Non-constant pointer to non-constant data
Node *const ptr;  // Constant pointer to non-constant data
const Node *ptr;  // Non-constant pointer to constant data
Node const *ptr;  // Same as above
const Node *const ptr;  // Constant pointer to constant data
Node const *const ptr;  // Same as above

请注意,const Node 与最后一级的 Node const 相同,但 const 的位置与指针声明有关("*") 非常重要。

关于c++ - 如何将常量指针传递给类中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9765052/

相关文章:

C++ vector 指向指针的指针

c++ - 为什么可以将整数值赋给未初始化的指针

c++ - C++中类常量在哪里定义?

c++ - 我如何使用 S(*)(int)?

c++ - 在字符串文字内展开宏

c++ - Teamcenter |服务器|代码错误处理

c++ - 对如何在 c++ 中编写 for 循环(包括 for all 加法)感到困惑

c++ - 删除指向小部件 Qt C++ 的指针

C: 编译器警告 "return discards qualifiers from pointer target type"

c++: "pointer to const"指向的对象是否被认为是不变的或只是不可修改的?