Copying a C++ class with a member variable of reference type

后端 未结 7 2389
清酒与你
清酒与你 2020-12-30 06:06

I\'ve a class which stores a reference to its parent, the reference is passed in the constructor. If I try to copy an instance I get an error \"error C2582: \'operator =\' f

7条回答
  •  攒了一身酷
    2020-12-30 06:31

    I don't recommend this at all

    but if you are really gung ho about doing this:

    #include 
    
    MyClass::MyClass(const MyClass &rhs): parent(rhs.parent)
    {
    }
    
    MyClass &MyClass::operator=(const MyClass &rhs)
    {
        if (this!=&rhs)
        {
            this->~MyClass();
            new (this) MyClass(rhs);
        }
    
        return *this;
    }
    

提交回复
热议问题