带引用类成员的赋值操作符
Assignment operator with reference class member
只要从我之前的问题中产生新的问题,重载赋值操作符会导致递归警告,我被合理地敦促将此作为新问题发布。我在我的类Player中有一个引用类成员,我想实现这个类的复制构造函数和赋值操作符(=)。我必须提一下,目的是函数向量的良好工作。擦除,因为在我看来,没有擦除,它就不能正常工作。我使用矢量:vector allPlayers;类Player的成员是:
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;
}
如果要实现赋值操作符,是否必须避免使用reference作为类成员?地图成员呢?我最终应该如何实现赋值操作符?
另一个我不知道的最重要的问题是,当我擦除保存Player的vector的迭代器时,指针类成员所指向的对象会发生什么。任何帮助吗?
c++ '引用'只能初始化,不能赋值:
int value1(1), value2(2);
int& ref1 = value1; // OK
int& ref2; // compile error: reference not initialized
int& ref3=ref1; // OK: ref3 refers to the same variable as ref1
ref1=value2; // equivalent to 'value1=value2'.
因此,包含引用的对象也只能初始化!确实如此:如果你需要对一个类赋值,这个类不能有引用成员变量。(事实上,可以,但是赋值不能使这些成员指向另一个位置)
当你想到这个,它是有道理的:
引用概念为另一个变量定义了"别名"。混叠意味着你对引用做的任何事情,实际上都是对被引用的位置做的。当你对这个别名应用赋值时,实际上你赋值给了引用的位置。如果您能够使用赋值使引用指向不同的位置,那么引用的目的就会丢失。
如果需要后者,则应该使用指针。
当需要赋值操作符时,我会避免使用引用成员。如果您使用(智能)指针,则可以直接执行
Player &operator=(Player const &other)
{
bankPtr = other.bankPtr;
// copy other members
}
在当前情况下,bank = other.bank
将复制other.bank
的内容,而不是将this->bank
指向other.bank
引用的内容。
对于multimap
类型的成员,它们可以毫无问题地复制,但请记住,您将获得键的"深度"副本(因为它们是string
类型),但值的"浅"指针副本,因此您最终获得共享状态。您可能希望使用shared_ptr
作为值
这确实是对c++设计的一个hack,但是你可以在'this'上使用placement new来做到这一点。例如
MyClass::MyClass(ReferenceType& referenceTarget):
myReference(referenceTarget)
{}
MyClass& MyClass::operator=(const MyClass& other)
{
new (this) MyClass(other.myReference);
return *this;
}
- 模板的赋值运算符(成员函数)实现的正确语法
- 将字符串文本传递给函数并赋值给成员变量
- c++中的重载赋值操作符
- c++类继承和赋值操作符
- 带引用类成员的赋值操作符
- 复制构造函数,赋值操作符重载
- c++派生类赋值操作符
- 通过调用Move赋值操作符实现Move构造函数
- 带有映射的赋值操作符
- 单参数构造函数和赋值操作符
- 如何从复制赋值操作符调用复制构造函数
- c++复制构造函数,重载赋值操作符,方法get()
- 用于具有const数据成员的类的move和右值赋值操作符
- 类赋值操作符和复制构造函数
- 赋值操作符重载
- 为具有引用成员变量的类创建赋值操作符
- 在复制赋值操作符中赋值基类成员
- 从模板化的类赋值操作符访问私有成员变量
- 如何处理赋值操作符和复制构造函数中的引用数据成员
- 为什么重载复合赋值操作符可以是非成员函数