简体   繁体   English

指针转换错误C ++

[英]pointer conversion error c++

I write a simple list class that part of is look like that: When I try to build the project the compilers shows 3 errors that one of them is with pointer conversion problems and I cant get why: 我写了一个简单的list类,一部分看起来是这样的:当我尝试构建项目时,编译器显示3个错误,其中一个是指针转换问题,我无法理解为什么:

Compiler error says: 编译器错误说:

  1. 'MyList::Node *MyList::begin(void)': cannot convert 'this' pointer from 'const MyList' to 'MyList &' 'MyList :: Node * MyList :: begin(void)':无法将'this'指针从'const MyList'转换为'MyList&'
  2. 'MyList::Node *MyList::end(void)': cannot convert 'this' pointer from 'const MyList' to 'MyList &' 'MyList :: Node * MyList :: end(void)':无法将'this'指针从'const MyList'转换为'MyList&'
  3. 'MyList::create': no overloaded function takes 1 arguments 'MyList :: create':没有重载函数接受1个参数

The class(only little part..) 上课(只有一小部分。)

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)
{
    ...
}

You are calling 你在打电话

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

Where rhs is a const object. 其中rhs是const对象。 But you are calling begin and end that requires the object to not be const. 但是您正在调用要求对象不为const的beginend Either change 要么改变

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

to

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

Or make begin and end work for const objects. 或使const对象的beginend工作。 ie node_iterator begin() const { return first; } node_iterator begin() const { return first; } node_iterator begin() const { return first; }

Fix this then work on any other compiler errors/warnings. 解决此问题,然后对其他任何编译器错误/警告进行处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM