如何将常量指针传递到类中的方法

How to pass a constant pointer to a method in a class

本文关键字:方法 常量 指针      更新时间:2023-10-16

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

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

当我编译时,它给出了一个编译错误:从"const Node*"到"Node*"的转换无效

有没有一种方法可以传递指向常量数据的指针?

您做得对,但编译器抱怨是对的:您将"指向常量Node的指针"分配给类型为"指向非常量Node的指针"的变量。如果你以后修改this->next,你就违反了"我不会修改next指向的变量

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

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

还要注意"指向const数据的指针"answers"指向数据的const指针"之间的区别。对于单层指针,就其const性质而言,有4种类型的指针:

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相对于指针声明("*")的位置非常重要。

有没有一种方法可以传递指向常量数据的指针?

是的。使用代码中显示的Node const*(或const Node*)。

要修复编译器错误,您有3个选择:

  1. Node::Node()应该接收一个非常数指针,以便可以分配给this->next
  2. 更改设计并将Node::next声明为Node const*
  3. Typecast,this->next = const_cast<Node*>(next);

使用第三种解决方案时应格外小心,否则可能会导致未定义的行为。

It also works with pointers but one has to be careful where ‘const’ is put as that determines whether the pointer or what it points to is constant. For example,
    const int * Constant2
declares that Constant2 is a variable pointer to a constant integer and
    int const * Constant2
is an alternative syntax which does the same, whereas
    int * const Constant3
declares that Constant3 is constant pointer to a variable integer and
    int const * const Constant4
declares that Constant4 is constant pointer to a constant integer. Basically ‘const’ applies to whatever is on its immediate left (other than if there is nothing there in which case it applies to whatever is its immediate right).

http://duramecho.com/ComputerInformation/WhyHowCppConst.html我想这个链接会对你有所帮助。你需要知道const的意思。祝你好运