【问题标题】:pointer conversion error c++指针转换错误 C++
【发布时间】:2017-12-25 08:40:04
【问题描述】:

我编写了一个简单的list 类,其中一部分如下所示: 当我尝试构建项目时,编译器显示 3 个错误,其中一个是指针转换问题,我不明白为什么:

编译器错误提示:

  1. “MyList::Node *MyList::begin(void)”:无法将“this”指针从“const MyList”转换为“MyList &”
  2. “MyList::Node *MyList::end(void)”:无法将“this”指针从“const MyList”转换为“MyList &”
  3. 'MyList::create':没有重载函数需要 1 个参数

类(只有一小部分..)

template<class T>
class MyList
{   
public:

    typedef T* iterator;
    typedef const T* const_iterator;
    typedef T value_type;
    typedef T& reference;
    typedef const T& const_reference;
    struct Node
    {
        T data;
        Node* prev;
        Node* next;
    };
    typedef Node* node_iterator;


    node_iterator begin() { return first; }
    node_iterator end() { return last; }

    ...

    MyList() { create(); }//default constructor
    MyList(size_type n, const T& val = T()){create(n, val);}
    MyList(const MyList& l) { create(l.begin(), l.end()); }//copy constructor
    MyList& operator=(const MyList&);//assignment operator
    ~MyList() { uncreate(); }

private:

    node_iterator first;
    node_iterator last;
    ...
    ...

};

MyList<T> & MyList<T>::operator=(const MyList& rhs)
{
    if (&rhs != this)
    {
        uncreate();
        create(rhs.begin(), rhs.end());
    }
    return *this;
}

template<class T>
void MyList<T>::create(node_iterator a, node_iterator b)
{
    ...
}

【问题讨论】:

  • 请提供minimal reproducible example。正如目前所写,我们无法在此处重现您的问题。
  • operator=() 中,参数rhsconst 引用。 create(rhs.begin(), rhs.end()) 尝试调用非const 成员函数。这是不允许的。

标签: c++ pointers


【解决方案1】:

你在打电话

create(rhs.begin(), rhs.end());

其中rhs 是一个常量对象。但是您正在调用 beginend,这要求对象不是 const。要么改变

 MyList<T> & MyList<T>::operator=(const MyList& rhs)

 MyList<T> & MyList<T>::operator=(MyList& rhs)

或者使 beginend 为 const 对象工作。即node_iterator begin() const { return first; }

修复此问题,然后处理任何其他编译器错误/警告。

【讨论】:

    猜你喜欢
    • 2012-11-02
    • 1970-01-01
    • 1970-01-01
    • 2016-08-24
    • 2017-08-29
    • 2021-06-06
    • 2021-09-20
    • 2023-03-05
    相关资源
    最近更新 更多