簡體   English   中英

C ++無法將參數從'* type'轉換為'const type&'

[英]C++ Cannot Convert parameter from '*type' to 'const type &'

以下操作是收銀機的一部分。

為了生成帳單,我應該對產品進行計數:
1.每個產品一次添加到帳單中。
2.如果此清單中已經存在該產品,則其數量將增加。

void CashRegister::countProducts()
{
OMIterator<Product*> iter(itsProduct);
CountedProduct* cp;
Product* p;

// Iterate through all products counting them
while (*iter) {
  // get the next product
  p = *iter;

  // has this already been added?
  cp = getItsCountedProduct(p->getBarcode());

  // If it does not exist then add it else increment it
  if (NULL==cp) {
    addItsCountedProduct(p->getBarcode(), new CountedProduct(p));
  } else {                                                       
    cp->increment();
  }                 
  // point to next
  ++iter;
}    

和:

void CashRegister::addItsCountedProduct(int key, CountedProduct* p_CountedProduct) 
{
if(p_CountedProduct != NULL)
    {
        NOTIFY_RELATION_ITEM_ADDED("itsCountedProduct", p_CountedProduct, false, false);
    }
else
    {
        NOTIFY_RELATION_CLEARED("itsCountedProduct");
    }
itsCountedProduct.add(key,p_CountedProduct);

}

我收到以下錯誤:
錯誤C2664:“ CountedProduct :: CountedProduct”:無法將參數1從“ Product *”轉換為“ const CountedProduct&”

錯誤是對此行的引用:
addItsCountedProduct(p->getBarcode(), new CountedProduct(p));

有任何想法嗎?

如果該函數采用const CountedProduct&則不應創建指針。

addItsCountedProduct(p->getBarcode(), new CountedProduct(p))  // wrong

您應該只在堆棧上創建一個實例

addItsCountedProduct(p->getBarcode(), CountedProduct(p))

語句new CountedProduct(p)返回一個指針,類型為: CountedProduct* 您想要一個常量引用: const CountedProduct &

要解決此問題,請替換該行:

addItsCountedProduct(p->getBarcode(), new CountedProduct(p));

與:

addItsCountedProduct(p->getBarcode(), CountedProduct(p));

另外,調用new CountedProduct(p)而不保留指向所創建對象的指針將導致內存泄漏。 它是在堆上分配的內存,您以后無法釋放該內存(使用delete調用)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM