简体   繁体   English

重载减法运算符 cpp

[英]Overloading subtraction operator cpp

I'm a bit new to object oriented programming in c++ and I've been trying to overload subtraction(-) operator in c++ for a Complex class I created.我对 C++ 中的面向对象编程有点陌生,我一直在尝试在 C++ 中为我创建的 Complex 类重载减法(-)运算符。 It is working fine except my program is terminating abnormally.除了我的程序异常终止外,它工作正常。
Below is what I've been trying to do:以下是我一直在尝试做的事情:

#include<iostream>
#include<cstdlib>
class Complex{
    //Data-members
private:
    int re, im;

    //methods
public:
    //Constructor
    Complex(){ /*default Constructor*/ }
    Complex(const int& re_, const int& im_):re(re_), im(im_){}
    //Subtraction(-) operator overloading
    Complex operator-(const Complex& op)
    {
        Complex res(this->re - op.re, this->im - op.im);
        return res;
    }
    //get-set methods for re
    int getReal(){ return re; }
    void setReal(const int& re){ this->re = re; }
    //get-set methods for im
    int getImaginary(){ return im; }
    void setImaginary(const int& im){ this->im = im; }
    //Destructor
    ~Complex(){ free(this); }
};

int main()
{
    Complex a(2, 3), b(3, 5);
    Complex d = a - b;
    std::cout<<"d.re = "<<d.getReal()<<" d.im = "<<d.getImaginary()<<"\n";
    return 0;
}

Can anyone please explain the cause of error.任何人都可以请解释错误的原因。

Never ever do free(this) , least of all in the destructor.永远不要做free(this) ,尤其是在析构函数中。 The memory for the objects will be free'd outside of the destructor, either by the compiler generated code or by the user doing delete or delete[] .对象的内存将在析构函数之外由编译器生成的代码或用户执行deletedelete[]

In fact this is the cause of your problem, as the objects created never were allocated with malloc .事实上,这就是您的问题的原因,因为创建的对象从未使用malloc分配。

The proper solution in this case is to not only remove the free call, but the whole destructor, since it's not needed for this class.在这种情况下,正确的解决方案是不仅删除free调用,而且删除整个析构函数,因为此类不需要它。

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

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