C++ 如何向类中的方法传递常量指针
我有一个节点类的构造函数:C++ 如何向类中的方法传递常量指针,c++,pointers,constants,C++,Pointers,Constants,我有一个节点类的构造函数: Node::Node(int item, Node const * next) { this->item = item; this->next = next; } 当我编译时,它给出了一个编译错误:从“const Node*”到“Node*”的转换无效 有没有一种方法可以传递指向常量数据的指针?你做得很正确,但编译器抱怨是对的:你给变量分配了一个“指向常量节点的指针”,类型为“指向非常量节点的指针”。如果以后修改this->next,则
Node::Node(int item, Node const * next)
{
this->item = item;
this->next = next;
}
当我编译时,它给出了一个编译错误:从“const Node*”到“Node*”的转换无效
有没有一种方法可以传递指向常量数据的指针?你做得很正确,但编译器抱怨是对的:你给变量分配了一个“指向常量
节点的指针”
,类型为“指向非常量节点的指针”。如果以后修改this->next
,则违反了“我不会修改next
所指向的变量”的约定
简单的解决方法是将next
声明为指向非常量数据的指针。如果变量this->next
在节点
对象的生命周期内永远不会被修改,那么您也可以将类成员声明为指向常量
对象的指针:
class Node
{
...
const Node *next;
}:
还要注意“指向常量
数据的指针”和“常量
指向数据的指针”之间的区别。对于单级指针,就其常量
而言,有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 const
相同,但是关于指针声明(“*
”)的const的位置非常重要
是否有方法传递指向常量数据的指针
是。如您在代码中所示,使用Node const*
(或const Node*
)
要修复编译器错误,您有3种选择:
Node::Node()
应接收一个非常量指针,以便
它可以分配给this->next
更改设计并声明Node::next
同时声明一个Node const*
Typecast,this->next=const_cast(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).
我想这个链接会对你有所帮助。你需要知道const是什么意思。祝你好运