_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. 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)

有帮助吗?

解决方案

This is an infinite recursion. Function swap() works like this:

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

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.

其他提示

Function swap in turn call the copy assignment operator. 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归因
不隶属于 StackOverflow
scroll top