C++:当运算符=重载时出现 EXC_BAD_ACCESS

问题描述 投票:0回答:1

之前问过operator=重载错误,问题由于重复而被关闭,试图修复代码,然后出现了新的错误..

const 限定后旧错误消失了, 但是当尝试

SetName
ItemType
时,由于
EXC_BAD_ACCESS (code=2, address=[address])
.

,出现了一个新错误(这是一件好事?)

[最小可重现代码]

主.cpp

#include "DoublySortedLinkedList.h"

int main() {
    DoublySortedLinkedList<ItemType> m_List;
}

项目类型.h

#include <string>

using namespace std;

class ItemType {
public:
    ItemType(int Id) {
        m_Id = Id;
        m_sName = "";
    }

    int GetId() const {
        return m_Id;
    }

    string GetName() const
    {
        return m_sName;
    }

    void SetName(const string &inName) {
        m_sName = inName;
    }

    void SetId(int inId) {
        m_Id = inId;
    }

    ItemType& operator=(ItemType const &data) {
        this->SetName(data.GetName());
        this->SetId(data.GetId());
        return *this;
    }
protected:
    int m_Id;
    string m_sName; 
};

DoubleIterator.h

#include "DoublySortedLinkedList.h"

template<typename T>
struct DoublyNodeType;
template<typename T>
class DoublySortedLinkedList;

template <typename T>
class DoublyIterator
{
    friend class DoublySortedLinkedList<T>;
public:
    DoublyIterator(const DoublySortedLinkedList<T>& list) : m_List(list), m_pCurPointer(list.m_pFirst) {};
    T Next();
private:
    const DoublySortedLinkedList<T>& m_List;
    DoublyNodeType<T>* m_pCurPointer;
};

template <typename T>
T DoublyIterator<T>::Next() {
    m_pCurPointer = m_pCurPointer->next;
    return m_pCurPointer->data;
}

DoubleSortedLinkedList.h

#include "ItemType.h"
#include "DoublyIterator.h"

# define min ItemType(INT_MIN)
#define max ItemType(INT_MAX)

template<typename T>
class DoublyIterator;

template <typename T>
struct DoublyNodeType
{
    T data;
    DoublyNodeType* prev;
    DoublyNodeType* next;
};

template <typename T>
class DoublySortedLinkedList
{
    friend class DoublyIterator<T>;
public:
    DoublySortedLinkedList();
private:
    DoublyNodeType<T>* m_pFirst;
    DoublyNodeType<T>* m_pLast;
    int m_nLength;
};

template <typename T>
DoublySortedLinkedList<T>::DoublySortedLinkedList() {
    m_pFirst->data = min; // header // this is where the new error occurs when debugging
    m_pLast->data = max; // trailer // probably this will cause the error
    m_nLength = 0;
}
c++ operator-overloading exc-bad-access
1个回答
0
投票

感谢您指出我的代码中的不良做法的评论! 为了回答

EXC_BAD_ALLOC
部分,我只是愚蠢地没有初始化
m_pFirst
m_pLast
动态分配为
new DouibleNodeType

我将尝试改进我使用宏和发布最小可重现代码的实践!

© www.soinside.com 2019 - 2024. All rights reserved.