[英]Using overloaded >> operator inside class constructor to initialise it
[英]Adding a constructor using an overloaded operator
我正在使用鏈接袋,需要使用重載運算符創建袋的副本。 當前代碼給了我一個空白的袋子。 它應該返回我在文本文件中輸入的值。 問題出在我要重載的操作員身上。
template<class ItemType>
LinkedBag<ItemType>::LinkedBag(const LinkedBag<ItemType>& aBag)
{
itemCount = aBag.itemCount;
Node<ItemType> *origChainPtr = aBag.headPtr;
if (origChainPtr == nullptr)
{
headPtr = nullptr; // original bag is empty; so is copy
} else
{
// copy first node
headPtr = new Node<ItemType>();
headPtr->setItem(origChainPtr->getItem());
headPtr->setCount(origChainPtr->getCount());
// copy remaining nodes
Node<ItemType> *newChainPtr = headPtr;
origChainPtr = origChainPtr->getNext();
while (origChainPtr != nullptr)
{
// get next node values from original chain
ItemType nextItem = origChainPtr->getItem();
int nextCount = origChainPtr->getCount();
// create a new node containing the next 2D point
Node<ItemType> *newNodePtr = new Node<ItemType>(nextItem, nextCount);
// link new node to end of new chain
newChainPtr->setNext(newNodePtr);
// advance pointers
newChainPtr = newChainPtr->getNext();
origChainPtr = origChainPtr->getNext();
}
newChainPtr->setNext(nullptr);
}
} // end copy constructor
我嘗試創建的此重載運算符將創建Linkedbag的深層副本。
template<class ItemType>
LinkedBag<ItemType>& LinkedBag<ItemType>::operator=(const LinkedBag<ItemType>& rhs)
{
if (this != &rhs)
{
this->clear(); // Deallocate left-hand side
//copyBagNode(rhs); // Copy list nodes
Node<ItemType> *origChainPtr = rhs.headPtr;
itemCount = rhs.itemCount; // Copy size of list
} // end if
// end operator=
return *this; // by convention, operator= should return *this
}
就像Ali rhs.headPtr
在評論中所說的那樣, rhs.headPtr
不會復制到this->headPtr
,就像復制構造函數定義中那樣
template<class ItemType>
LinkedBag<ItemType>& LinkedBag<ItemType>::operator=(const LinkedBag<ItemType>& rhs)
{
if (this != &rhs)
{
this->clear(); // Deallocate left-hand side
itemCount = rsh.itemCount;
Node<ItemType> *origChainPtr = rsh.headPtr;
if (origChainPtr == nullptr)
{
headPtr = nullptr; // original bag is empty; so is copy
} else
{
// copy first node
headPtr = new Node<ItemType>();
headPtr->setItem(origChainPtr->getItem());
headPtr->setCount(origChainPtr->getCount());
// copy remaining nodes
Node<ItemType> *newChainPtr = headPtr;
origChainPtr = origChainPtr->getNext();
while (origChainPtr != nullptr)
{
// get next node values from original chain
ItemType nextItem = origChainPtr->getItem();
int nextCount = origChainPtr->getCount();
// create a new node containing the next 2D point
Node<ItemType> *newNodePtr = new Node<ItemType>(nextItem, nextCount);
// link new node to end of new chain
newChainPtr->setNext(newNodePtr);
// advance pointers
newChainPtr = newChainPtr->getNext();
origChainPtr = origChainPtr->getNext();
}
newChainPtr->setNext(nullptr);
}
}
// end operator=
return *this; // by convention, operator= should return *this
}
但是使用重復的代碼,最好使用共享的附加操作來完成這項工作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.