对对象的“无匹配函数调用”函数调用

时间:2018-07-13 02:05:01

标签: c++ g++

我遇到一个问题,在item.GetName()中的某个项目上进行函数调用的每个位置(例如vector<ItemToPurchase> items),都会收到错误消息:no matching function for call to vector<ItemToPurchase,__default_alloc_template<false,0> >::at (int &)我是一直到处都是,甚至都不理解“没有匹配的调用函数”的含义。

g ++消息示例

ShoppingCart.cpp: In method `bool ShoppingCart::CheckCartForItem(class 
string)':
ShoppingCart.cpp:22: no matching function for call to 
`vector<ItemToPurchase,__default_alloc_template<false,0> >::at (int &)'

ShoppingCart.h:

#ifndef SHOPPINGCART_H
#define SHOPPINGCART_H

#include "ItemToPurchase.h"
#include <vector>

class ShoppingCart
{
public:
    ShoppingCart(string customerName = "none", string dateCreated = "January 1, 2016");
    *other functions*
    bool CheckCartForItem(string itemName);
    void AddItemToCart(ItemToPurchase item);
    *more functions*
private:
    *other variables*
    std::vector<ItemToPurchase> items;
};
#endif

ShoppingCart.cpp

#include "ShoppingCart.h"
#include <iostream>

ShoppingCart::ShoppingCart(string customerName, string dateCreated)
{
    this->customerName = customerName;
    this->dateCreated = dateCreated;
}

bool ShoppingCart::CheckCartForItem(string itemName)
{
    if (items.size() == 0) //if cart is empty
        return false;

    for (int i = 0; i < items.size(); i++)
    {
        if (items.at(i).GetName() == itemName) //<- Problem here
            return true;
    }

    return false;
 }

void ShoppingCart::AddItemToCart(ItemToPurchase item) 
{   
    if (CheckCartForItem(item.GetName()) == false) //if item not in cart
        items.push_back(item);
    else
        cout << "Item is already in cart. Nothing added." << endl;
}

ItemToPurchase.h

#ifndef ITEMTOPURCHASE_H
#define ITEMTOPURCHASE_H

#include <string>
using namespace std;

class ItemToPurchase
{
public:
    ItemToPurchase(string name = "none", string description = "none", double 
price = 0.0, int quantity = 0);
    void SetName(string);
    string GetName();
    *other functions*
private:
    string itemName;
    *other variables*
};

#endif // ITEMTOPURCHASE_H

ItemToPurchase.cpp

#include "ItemToPurchase.h"
#include <iostream>
#include <iomanip>


ItemToPurchase::ItemToPurchase(string name, string description, double 
price, int quantity)
{
    itemName = name;
    itemDescription = description;
    itemPrice = price;
    itemQuantity = quantity;
}

void ItemToPurchase::SetName(string name){ itemName = name; }

string ItemToPurchase::GetName() { return itemName; }

1 个答案:

答案 0 :(得分:0)

由于在这种情况下,您不使用索引变量,因此可以使用range-based for loop进行迭代:

for (auto& item : items) {
    if (item.GetName() == itemName) {
        [...]

std::vector:at需要一个std::vector::size_type(通常定义为std::size_t)。在使用基于索引的访问器时,更改i的类型应使其兼容:

for (std::vector<ItemToPurchase>::size_type i = 0; i < items.size(); ++i) {
    if (items.at(i).GetName() == itemName) {
        [...]