如何将常量指针传递到类中的方法
How to pass a constant pointer to a method in a class
我有一个Node类的构造函数:
Node::Node(int item, Node const * next)
{
this->item = item;
this->next = next;
}
当我编译时,它给出了一个编译错误:从"const Node*"到"Node*"的转换无效
有没有一种方法可以传递指向常量数据的指针?
您做得对,但编译器抱怨是对的:您将"指向常量Node
的指针"分配给类型为"指向非常量Node
的指针"的变量。如果你以后修改this->next
,你就违反了"我不会修改next
指向的变量
简单的解决方法就是将next
声明为指向非常数数据的指针。如果变量this->next
在Node
对象的生命周期内永远不会被修改,那么您也可以将类成员声明为指向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个选择:
Node::Node()
应该接收一个非常数指针,以便可以分配给this->next
- 更改设计并将
Node::next
声明为Node const*
- 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
的意思。祝你好运
相关文章:
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 是否有内置方法可以强制转换为不同的基础类型,但保留常量限定符?
- 为什么常量方法可以采用非常量引用?
- 常量方法中的非常量 lambda 捕获
- 友元方法作为常量
- 一个模板方法,用于同时接受常量和非常量参数
- 使用大量已知常量变量的正确方法
- 使用迭代器替换映射中的常量项的方法
- 一种优雅或至少可行的方法,用于使用和接受具有重载方法和运算符的不同大小的文字数组常量
- 初始化不是整数的巨大常量多维数组的最佳方法是什么?
- Gmock 常量方法不调用,而是调用原始方法
- 为什么我们需要常量方法?
- 从模块导出全局常量的正确方法是什么?
- 模板常量/非常量方法
- 定义常量变量的最佳方法
- 常量字符*的模板方法专用化
- 常量静态成员函数:有另一种方法可用吗?
- 使方法常量后声明不兼容
- c++ 是否提供了一种使整个结构常量(不可修改)的方法?
- 当底层OpenGL状态被修改时,我应该声明一个方法常量吗