【问题标题】:C++ Cannot Convert parameter from '*type' to 'const type &'C++ 无法将参数从 '*type' 转换为 'const type &'
【发布时间】:2015-12-03 12:50:51
【问题描述】:

以下操作是收银机的一部分。

为了生成账单,我应该对产品进行计数:
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);

}

我收到以下错误:
error C2664: 'CountedProduct::CountedProduct' : cannot convert parameter 1 from 'Product *' to 'const CountedProduct &'

错误是对这一行的引用:
addItsCountedProduct(p-&gt;getBarcode(), new CountedProduct(p));

有什么想法吗?

【问题讨论】:

  • 您没有显示CountedProduct 的构造函数,但pProduct *,错误似乎表明您只有CountedProduct(const CountedProduct&amp;)
  • C++ 不是 C# 或 Java。不要被相似的语法或熟悉的关键字误导,这是完全不同的语言、编程文化和范式集。在继续之前,您可能想先了解有关“C++ 方法”的更多信息:The Definitive C++ Book Guide and List(从最佳实践和中间部分开始)。

标签: c++ pointers constants


【解决方案1】:

如果函数采用const CountedProduct&amp;,那么您不应该创建指针。

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

你应该只在堆栈上创建一个实例

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

【讨论】:

    【解决方案2】:

    语句new CountedProduct(p) 返回一个指针,类型:CountedProduct*。你想要一个常量引用:const CountedProduct &amp;

    要解决此问题,请替换以下行:

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

    与:

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

    顺便说一句,调用new CountedProduct(p) 并且不保留指向所创建对象的指针会导致内存泄漏。它是在堆上分配的内存,您以后无法释放该内存(通过 delete 调用)。

    【讨论】:

    • 谢谢,但这能回答我的问题吗?
    猜你喜欢
    • 2012-08-17
    • 2020-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-03
    • 1970-01-01
    • 2015-09-24
    • 1970-01-01
    相关资源
    最近更新 更多