c++ - 状态错误 C2440 :" ' =': cannot convert from ' const FDHNode<ItemType> *' to ' FDHNode<ItemType> *'"?

标签 c++

我一直收到错误“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是常数。

有两种方法可以解决这个问题,具体取决于某些事情:

  1. 如果next指针实际上是可以更改的,然后您必须修改 NEXTPTR 的定义这样它就不是 const .如果这样做,您的函数声明将是这样的:void FDHNode<ItemType>::setNext(FDHNode<ItemType>* NEXTPTR)
  2. 或者参数确实是一个常量,在这种情况下你应该定义你的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/

相关文章:

c++ - gsl_complex 导致内存溢出

c++ - C++ 中的 const_cast 规则

c++ - C++ 库命名空间和 C linux 函数之间的名称冲突

c++ - MySQL插件架构

c++ - std::set of std::string 不等式实现

c++ - 如何将 constexpr 作为模板参数传递?

c++ - 无法读取串行输入

c++ - 在解析器中提升 Spirit 段错误

c++ - 需要一些想法来销毁 N :M relation

c++ - Qt QLabel HTML 字体大小严重失败