访问冲突写入位置0x00000028

时间:2017-11-22 00:43:40

标签: c++

我在分配操作员方面遇到了一些问题。虽然没有红色下划线错误,但是当我编译程序时会打破

emp1 = emp2;
在main.cpp中,一切正常,直到我添加了赋值操作函数。

任何建议都将不胜感激。

编辑:我想我应该展示与问题相关的特定代码而不是整个事情。

这是我写的:

ListOfEmp.h

public:
    ListOfEmp();
    ListOfEmp(const ListOfEmp &);
    ~ListOfEmp();
    const ListOfEmp& operator=(const ListOfEmp e);

};

ListOfEmp.cpp

ListOfEmp::ListOfEmp():head(NULL)
{
}

ListOfEmp::ListOfEmp(const ListOfEmp &e) {
    *this = e;
}

ListOfEmp::~ListOfEmp()
{
    clear();
}


const ListOfEmp& ListOfEmp::operator=(const ListOfEmp e){
    if (this != &e) {
        clear();
        EmpNode* copy = NULL;
        EmpNode* orig = e.head;
        while (orig != NULL) {
            if (head = NULL) {
                head = copy = new EmpNode((orig->emp).name, (orig->emp).salary);
            }
            else {
                copy->next = new EmpNode((orig->emp).name, (orig->emp).salary);
                copy = copy->next;
            }

            orig = orig->next;
        }
    }
    return *this;
}

void ListOfEmp::clear() {
    EmpNode* temp = head;
    while (temp != NULL) {
        temp = temp->next;
        delete head;
        head = temp;
    }
}

Main.cpp的

int main() {
    ListOfEmp emp1;
    emp1.insertAtfront("John", 20000.00);
    emp1.insertAtfront("Dave", 24500.50);
    emp1.insertAtfront("Joshua", 33567.60);
    emp1.deleteMostRecent();
    emp1.getSalary("Dave");
    cout << endl;
    cout << emp1;
    cout << endl;

    ListOfEmp emp2;
    emp2.insertAtfront("Julio", 54000.00);
    emp2.insertAtfront("Mike", 12000.00);
    emp2.getSalary("Mike");
    cout << endl;
    cout << emp2;
    cout << endl;
    emp1 = emp2;
    cout << emp1;
    cout << endl;
    cout << emp2;
    system("pause");
}

2 个答案:

答案 0 :(得分:1)

ListOfEmp::ListOfEmp(const ListOfEmp &e) {
    *this = e;
}

围绕赋值运算符设置复制构造函数。不幸的是,赋值运算符

const ListOfEmp& ListOfEmp::operator=(const ListOfEmp e){
    ...
}

通过值分配ListOfEmp,调用复制构造函数,该构造函数调用赋值操作符,该操作符调用调用赋值运算符的赋值运算符,该运算符调用复制构造函数,该构造函数调用调用复制构造函数的赋值运算符。 ....

不受控制的递归。

解决方案通过引用传递

const ListOfEmp& ListOfEmp::operator=(const ListOfEmp & e){
    ...
}

并以相反的方式重写,基于复制构造函数的赋值运算符,以利用ever-popular Copy and Swap Idiom

如果您选择第一个选项,请注意赋值运算符过于复杂且存在逻辑错误

if (head = NULL) // Whoops. Annihilated head! Should be head == NULL

并且不完整的代码为未提供的代码中的其他错误留下了足够的空间。

scohe001还正确地指出head未在复制构造函数中初始化。这很可能不是导致崩溃的错误。

答案 1 :(得分:0)

在阅读OP的问题和一个体面的答案值得赞同之后,他们的帮助,但仍然缺乏一些回答只是因为OP缺乏提交最小,完整,和可验证的例子我倾向于认为OP是以下的受害者:

以及社区从未提交的来源无法看到的任何其他看不见的问题或语言特定的语法错误。

相关问题