带有参考类成员的赋值运算符 [英] Assignment operator with reference class member

查看:84
本文介绍了带有参考类成员的赋值运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只要我以前的问题中出现了新问题,重载的赋值运算符会引起有关递归的警告,因此,我们有理由敦促我将其发布为新递归.我的类Player中有一个引用类成员,我想实现该类的复制构造函数和赋值运算符(=).我不得不提到目的是函数vector.erase的良好工作,因为没有它就我而言就不能正常工作.我使用向量:vector allPlayers;播放器类的成员是:

As long as new issues are growing out of my previous question Overloaded assignment operator causes warning about recursion, I was legitimately urged to post this as new one. I have a reference class member in my class Player and I want to implement the copy constructor and the assignment operator (=) of this class. I have to mention that the purpose is the fine working of the function vector.erase because without that it does not work properly as far as I am concerned. I use a vector: vector allPlayers; The members of the class Player are:

class Player
{

  private:
  int ID;
  int pMoney;
  int doubleIndicator;
  int squarePosition;
  Bank& bank;
  string pName;
  Square* capturedSquare;
  multimap<string, PropertySquare*> squaresColBought;
  multimap<string, House*> housesColBuilt;

}

如果要实现赋值运算符,是否必须避免将引用用作类成员?那地图成员呢?我最终应该如何实现赋值运算符?

Is it mandatory to avoid the use of reference as class member if I want to implement the assignment operator? What about the map members? How should I finally implement the assignment operator?

我不知道的另一个最重要的问题是,当我删除保存播放器的向量的迭代器时,指针类成员所指向的对象会发生什么.有帮助吗?

推荐答案

当您需要赋值运算符时,我将避免使用引用成员.如果您改用(智能)指针,则可以

I would refrain from using a reference member when you want an assignment operator. If you use a (smart) pointer instead, you can just do

Player &operator=(Player const &other)
{
    bankPtr = other.bankPtr;
    // copy other members
}

在当前情况下,bank = other.bank将复制other.bank的内容,而不是将this->bank指向other.bank引用的内容.

In the current situation, bank = other.bank will copy the contents of other.bank instead of pointing this->bank to the contents referenced by other.bank.

对于multimap类型的成员,可以毫无问题地复制它们,但是请记住,您将获得键的深层"副本(因为它们的类型为string),但是值的浅"指针副本,因此您最终会处于共享状态.您可能需要使用shared_ptr作为值.

As for the multimap-typed members, they can be copied without problems, but do keep in mind that you'll get a "deep" copy of the keys (since they're of type string) but a "shallow" pointer copy of the values, so you end up with shared state. You might want to use shared_ptr for the values.

这篇关于带有参考类成员的赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆