简体   繁体   English

重载运算符时发生SIGSEGV错误=

[英]SIGSEGV error when overloading the operator=

    _3DTocka operator=(_3DTocka _3D){
        swap(*this, _3D);
        return *this;
    }

//main()
_3DTocka _3Dx1(5, 9, 2), _3Dx2(_3Dx1); // first one is using constructor, second one copy constuctor and they both have 5,9,2
_3Dx1 = _3Dx2;

_3DTocka is the name of the class. _3DTocka是类的名称。 The code compiles and then the program gives SIGSEGV error instantly when it's ran.. and the IDE goes to move.h, line 167, code: swap(_Tp& __a, _Tp& __b) 代码经过编译,然后在运行时程序立即给出SIGSEGV错误。并且IDE继续移动。h,第167行,代码:swap(_Tp&__a,_Tp&__b)

This is an infinite recursion. 这是无限递归。 Function swap() works like this: 函数swap()的工作方式如下:

void swap(Type & a, Type & b) {
    Type tmp = a;   \
    a = b;          -> here it calls your operator=  
    b = tmp;        /
}

You have to assign all class atributes from _3D to this 您必须将_3D的所有类属性分配给此

this->a = _3D.a;
this->b = _3d.b;
...

Or you can use memcpy(this, &_3D, sizeof(_3D)) , but ONLY if your class doesn't contain other objects, but only basic types. 或者,您可以使用memcpy(this, &_3D, sizeof(_3D)) ,但是仅当您的类不包含其他对象,而仅包含基本类型时,才可以使用。

Function swap in turn call the copy assignment operator. 函数swap依次调用副本分配运算符。 So you will get recursive calls of the operator. 因此,您将获得操作员的递归调用。 You should define your own swap function for the class that will swap each data member of the objects. 您应该为将定义对象的每个数据成员的类定义自己的交换函数。

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

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