类析构函数导致重载+运算符的问题

问题描述

我无法弄清楚我的C ++类(使用Visual Studio)是什么问题。 Visual Studio没有给出任何期望的输出,只是说“退出,代码为-1073741819”。我使用原始指针创建了一个名为Complex的类,当调用no-args或参数化构造函数时,使用新的int分配内存,并且当变量超出范围时,析构函数使用delete关键字释放内存。我面临的唯一问题是,我的+运算符重载导致了问题,并且我很确定此问题与析构函数有关,当我删除析构函数代码时,+运算符可以正常工作。或者,当我不使用+运算符时,程序也可以正常工作。请帮我弄清楚代码。请不要对我说“这里不需要原始指针”,实际上我被告知要这样做(仅使用指针)。我坚持了好几个小时。
这是我的代码,请仔细阅读,包括+运算符重载代码和析构函数代码。

#include<iostream>
using namespace std;

class Complex {
private:
    int *real;
    int *complex;
    
public:
    // some declarations
    Complex();
    Complex(int,int);
    Complex(const Complex& source);
    Complex operator+ (const Complex& rhs);
    Complex& operator= (const Complex& rhs);
    void disp() {
        cout << "(" << *real << "," << *complex << ")" << endl;
    }
    // destructor
    ~Complex() {
        delete real;
        real = nullptr;
        delete complex;
        complex = nullptr;
    }
    
};

// no-args constructor
Complex::Complex() {
    real = new int;
    *real = 0;
    complex = new int;
    *complex = 0;
}
// parameterized constructor
Complex::Complex(int x,int y) : Complex() {

    *real = x;
    *complex = y;
}
//copy constructor
Complex::Complex(const Complex& source) {
    *(this->real) = *(source.real);
    *(this->complex) = *(source.complex);
}

// overloading + operator
Complex Complex::operator+ (const Complex &rhs) {
    int a,b;
    a = *(this->real) + *(rhs.real);
    b = *(this->complex) + *(rhs.complex);
    Complex temp(a,b);
    return temp;
}
// overloading = operator
Complex& Complex::operator= (const Complex& rhs) {
    
    *(this->real) = *(rhs.real);
    *(this->complex) = *(rhs.complex);
    return *this;

}

int main() {
    Complex n1(5,-9);
    Complex n2(5,-1);
    Complex n3;
    n3=n1 + n2;
    n3.disp();
    
    return 0;
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)