[英]Big 3 - Assignment operator
我正在开发二十一点游戏。 在我的二十一点游戏中,我创建了一个名为Dealer的类。 由于在堆上使用资源,因此我将“三巨头”添加到了该类中。 在我的int main()中,我创建了两个Dealer类型的指针并将它们设置为彼此。 但是,由于某种原因,当我运行调试器时,它不会转到在Dealer类中创建的Assign运算符。 谁能教育我为什么不使用在Dealer类中创建的赋值运算符? 为什么赋值运算符仅适用于Dealer类型的非指针变量?
class Dealer
{
public:
Dealer();
Dealer(Deck*);
Dealer& operator=(const Dealer&); // assign operator
Dealer(const Dealer&); //copy constructor
~Dealer();//deconstructor
private:
vector<Card*> myCards;
Deck *deckOfCards;
};
Dealer::Dealer()
{
deckOfCards = new Deck();
}
Dealer::Dealer(Deck *t)
{
deckOfCards = t;
}
//copy constructor
Dealer::Dealer(const Dealer& rightSide)
{
deckOfCards = new Deck();
for (size_t x= 0; rightSide.myCards.size(); x++)
{
myCards[x] = rightSide.myCards[x];//copying of the vector
}
}
//Assignment Operator
Dealer& Dealer::operator=(const Dealer& rhs)
{
if(this != &rhs)
{
delete deckOfCards;
for(size_t x = 0; x < myCards.size(); x++)
{
delete [] myCards[x];
}
myCards.clear();
deckOfCards = rhs.deckOfCards; //copy for Deck *deckOfCards
for (size_t x= 0; rhs.myCards.size(); x++)
{
myCards[x] = rhs.myCards[x];//copying of the vector
}
}
return *this;
}
//Destructor
Dealer::~Dealer()
{
delete deckOfCards;
for(size_t x = 0; x < myCards.size(); x++)
{
delete [] myCards[x];
}
myCards.clear();
}
int main()
{
Deck* p = new Deck();
Deck *b = new Deck();
p->shuffle();
p->Display();
b = p; //does not apply the assign operator
b->Display();
b->shuffle();
b->Display();
// Deck f;
// Deck g;
// f.shuffle();
// g = f; // This goes to the assignment operator function
// f.Display();
// g.shuffle();
// g.Display();
}
因为分配方法用于复制对象(从广义上讲,从技术上讲,从技术上讲,它可能应该是“分配”) 对象,而不是用于复制指向对象的普通指针。
根据定义,当您复制指针时,您希望它指向完全相同的对象,否则实际上不是副本。 因此,您获得的只是对象地址的副本,无需为此而调用任何成员函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.