C++ C2582 Compiler won't auto-generate default c'tor or = operator
setting aside the fact that I use getter/setter where the more experienced C++-programmer won't make use of them I have a problem with the following code:
#include "Player.h"
class Entity
{
public:
Entity::Entity(Player& _owner)
: owner(_owner) { }
Player &get_owner() { return this->owner; }
void set_owner(Player &_owner) { this->owner = _owner; }
private:
Player &owner;
};
This gives me a C2582 saying the 'operator =' is unavailable for Player in the set_owner function. My Player class looks like this:
class 开发者_如何学CLayer;
class Cell;
class Player
{
public:
Player();
void credit_to_balance(const long &_amount);
..more getter/setter..
private:
long balance;
Layer ¤t_layer;
Cell ¤t_cell;
};
Until now I thought my default constructor/destructor and = operator would !always! be constructed by the compiler if I haven't done it myself (and they are used throughout the program). Apparently this isn't the case this time as other classes would also complain about removing the manually inserted default c'tor from Player. I even tried to write a small example program that does exactly the same (even with forward declaration and members that are references) and it worked.
And in my opinion it definitely should, because it would only copy some references and an intrinsic type. This is why I did not yet try to write my own = operator as I see no difficulties for the compiler to do that for me. For me it would lead into the problem of having in mind to update it each time I'm introducing new members to my class.
So much for my thoughts on this problem. I hope you guys can show me what I'm missing :) Thanks in advance!
You cannot "reseat" a reference, not even a class member which is a reference. this->owner = _owner;
is not going to change what object the member refers to, it's attempting to modify the object this->owner
always has referred to and always will.
If you need your class to change what other object(s) it refers to, use pointer members instead of reference members. You can keep the same public interface and just use &
and *
operators to "convert".
The problem is simple. You have the references as members of your class:
Layer ¤t_layer;
and
Cell ¤t_cell;
Compiler cannot generate a constructor, since it would not know how to initialize these references, so you need to define your own constructor.
Player can't have a compiler generated default ctor because it has reference members. What is the compiler supposed to bind those references to?
精彩评论