我一直收到错误“C2440:” '=': cannot convert from 'const FDHNode *' to 'FDHNode *"而且我一辈子都弄不明白。这是我的代码和定义函数,其中问题显然来自。
template<class ItemType>
class FDHNode
{
private:
ItemType coeff; //Data item representing coefficient
ItemType expon; //Data item representing exponent
FDHNode<ItemType>* next; //Pointer to a next node
public:
FDHNode();
FDHNode(const ItemType& coeffi, const ItemType& expone);
FDHNode(const ItemType& coeffi, FDHNode<ItemType>* nextNodePtr);
void setCoeffi(const ItemType& aCoeffi);
void setExpon(const ItemType& anExpon);
void setNext(const FDHNode<ItemType>* NEXTPTR);
ItemType getCoeffi();
ItemType getExpon();
FDHNode<ItemType>* getNext();
void print();
};
template<class ItemType>
void FDHNode<ItemType>::setNext(const FDHNode<ItemType>* NEXTPTR)
{
next = NEXTPTR;
}
最佳答案
变量next
定义如下:
FDHNode<ItemType>* next; //Pointer to a next node
和变量NEXTPTR
定义如下:
const FDHNode<ItemType>* NEXTPTR
添加的const
有它的意义,说明它不能被修改。当您分配 NEXTPTR
时至 next
, 这成为一个问题,因为 next
可以修改,但是NEXTPTR
是常数。
有两种方法可以解决这个问题,具体取决于某些事情:
- 如果
next
指针实际上是可以更改的,然后您必须修改NEXTPTR
的定义这样它就不是const
.如果这样做,您的函数声明将是这样的:void FDHNode<ItemType>::setNext(FDHNode<ItemType>* NEXTPTR)
- 或者参数确实是一个常量,在这种情况下你应该定义你的
next
变量为const
以及。像这样:const FDHNode<ItemType>* next;
注意:有const_cast<>
这可以抛弃 const
-变量的性质。但是,如果您不知道这个问题的答案,那么您不太可能需要在此处强制转换,因为在这种情况下它弊大于利。
关于c++ - 状态错误 C2440 :" ' =': cannot convert from ' const FDHNode<ItemType> *' to ' FDHNode<ItemType> *'"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43218888/