【发布时间】:2012-03-19 04:31:12
【问题描述】:
我有一个 Node 类的构造函数:
Node::Node(int item, Node const * next)
{
this->item = item;
this->next = next;
}
编译时出现编译错误:从 'const Node*' 到 'Node*' 的无效转换
有没有办法传递指向常量数据的指针?
【问题讨论】:
我有一个 Node 类的构造函数:
Node::Node(int item, Node const * next)
{
this->item = item;
this->next = next;
}
编译时出现编译错误:从 'const Node*' 到 'Node*' 的无效转换
有没有办法传递指向常量数据的指针?
【问题讨论】:
您做得对,但编译器抱怨是对的:您将“指向 const Node 的指针”分配给类型为“指向非常量 Node 的指针”的变量.如果以后修改this->next,就违反了“我不会修改next指向的变量”的约定。
简单的解决方法是将next 声明为指向非常量数据的指针。如果变量this->next 在Node 对象的生命周期内真的永远不会被修改,那么您也可以将类成员声明为指向const 对象的指针:
class Node
{
...
const Node *next;
}:
还要注意“指向const 数据的指针”和“const 指向数据的指针”之间的区别。对于单级指针,关于它们的constness,有 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 个选择:
Node::Node() 应该接收一个非常量指针,以便
可以分配给this->next
Node::next 也是Node const*
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是什么意思。祝你好运。
【讨论】: