我正在尝试重载运算符+。
重要的是要说,operator +恰好获取了我想要获取的datat,但是一旦我将其发送给operator =,由于某种原因,其中的所有指针都会被删除。

Movie& Movie:: operator+ (const Movie& other) {

Movie toReturn,toCheck;
Worker* toAdd;
std::list<Worker*>::iterator checkSecond;
length > other.getLength() ?  toReturn=*this, toCheck=other : toReturn =
other , toCheck = *this;

//I WANT TO TAKE THE LONGER MOVIE, AND ADD THE WORKERS FROM THE SHORTER
  MOVIE TO THAT MOVIE

if(toCheck.getNumOfWorkers() > 0 ) //LOOK FOR WORKERS IN SHORT MOVIE

{
for (checkSecond=toCheck.getWorkersInMovie().begin(); checkSecond !=
toCheck.getWorkersInMovie().end(); ++checkSecond)
           {
                toAdd= (*checkSecond);
                toReturn.addWorker(toAdd);
                toAdd = NULL;


            } //END FOR
    }
}
}

*this=toReturn;
cout << "this is what my new object has after +" <<endl;
this->printMovie(); //PRINTS EXACTLY WHAT I EXPECT, WITH NEW WORKERS
return *this;

}


但是当我将其发送给运算符=不能按预期复制时,说工人数为0。
既是电影又是电影+电影

Movie& Movie:: operator= (const Movie& other) {

WHEN IT GETS HERE, MOVIE OTHER GETS DELETED..
return *this;

}


复制构造函数在所有情况下均按预期工作:

Movie::Movie(const Movie& toCopy) {

  cout << "inside copy" << endl;
 *this=toCopy;
}


救命...?

最佳答案

对于+之类的表达式调用运算符A + B。从语义上讲,此表达式不应更改A的状态,而应返回表示总和的新对象。

因此,对于重载+运算符,正确的签名应为:

Movie Movie::operator+ (const Movie& other) const { }


如果要避免创建此临时对象,则不应重载+运算符,而应重载+=,如下所示:

Movie& Movie::operator+= (const Movie& other) { }


由于+ =具有赋值语义,因此您可以修改对象。

遵循此规则将帮助您解决代码中遇到的问题。

关于c++ - 重载运算符+ C++ Eclipse,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34103543/

10-17 02:46