重载的赋值运算符会引起有关递归的警告 [英] Overloaded assignment operator causes warning about recursion

查看:234
本文介绍了重载的赋值运算符会引起有关递归的警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在一个类中实现重载的赋值运算符,以便vector.erase函数将按" vector ::用指针成员擦除".为了相同的目的,我也实现了一个复制构造函数.通过操作符的以下实现,我得到警告:

I need to implement the overloaded the assignment operator in a class so the vector.erase function will work properly as proposed in the answers to "vector::erase with pointer member". I have implemented also a copy constructor for the same purpose. By the following implementation of the operator I get the warning :

'Player :: operator =':在所有控制路径上递归,该函数将导致运行时堆栈溢出.

'Player::operator=' : recursive on all control paths, function will cause runtime stack overflow.

显然,Player::operator=的实现不正确.什么是正确的实现?

Apparently the implementation of Player::operator= is incorrect. What is the correct implementation?

//Copy constructor:
Player::Player(const Player& otherPlayer) {
   ...
}


Player& Player::operator=(const Player& rhs) {
    *this = Player(rhs);
    return *this;
}

多图的擦除功能是否与矢量相同?在多地图中使用时,我不会收到关于未实现重载operator=的错误,因为它在矢量中会发生.真相是什么?

Does the erase function of a multimap work on the same way as the vector? When I use in the multimap I do not receive errors about not implementing the overloaded operator= as it happens with vector. What is the truth?

此外,玩家还可以参考银行作为会员.我是否应该仅通过=分配引用?复制构造函数的目的是什么?

Also, the Player has a reference to a Bank as a member. Should I do the assignment of the reference just by =? What is then the purpose of the copy constructor?

推荐答案

您的问题是这一行:

*this = Player(rhs);

这将再次调用重载=方法,从而导致递归循环. 您应该分别分配所有成员:

This calls the overloaded = method again, resulting in a recursive loop. You should assign all members separately:

x = rhs.x;
y = rhs.y; // for example

编辑另外请注意,由于您传递的对象与实例方法属于同一类型的对象,因此您可以像访问公共成员一样访问私有成员.

EDIT Also note that as the object you are passing is the same type of object the instance method belongs to, you can access private members just like you normally would for public members.

EDIT2 据我所知,您不会想要复制参考,因为这意味着可以从两个对象访问同一Bank对象,这会破坏封装和可能会引起一些意想不到的问题.您没有使用指针有任何特定原因吗?如果bank对象是一个指针,则可以为bank重载=运算符,然后按常规进行分配:

EDIT2 As far as I am aware you would not want to copy a reference, because that means the same Bank object would be accessible from both objects which breaks encapsulation and would probably cause some unintended problems. Is there any specific reason you are not using pointers? If the bank object was a pointer, you could overload the = operator for the bank, and then assign it normally:

bank = rhs.bank;

关于复制构造函数和赋值运算符的区别,谷歌快速搜索打开了该链接:

As for the difference of Copy Constructors and Assignment Operators, a quick google search turned up this link: http://prashanth-cpp.blogspot.com/2007/01/assignment-operator-vs-copy-constructor.html

这篇关于重载的赋值运算符会引起有关递归的警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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