引发异常:读取访问冲突。这是对象数组中的nullptr

我是一名参加OOP课程的CS学生,我不知道如何解决此问题。我知道,当+ =运算符尝试将第一个元素添加到数组中时,“ this”为nullptr并引发异常,但是我不知道如何解决它。

购物清单标题看起来像这样:

#include "Groceries.h"

class ShoppingList{
    Groceries* list;
    int size = 0, capacity = 2;
public:
//methods
     ShoppingList& operator+=( const Groceries& c);

运算符+ =看起来像:

ShoppingList& ShoppingList::operator+=( const Groceries& c) {
    if (size == capacity) {
        Groceries* l1 = new Groceries[capacity * 2];
        l1 = list;
        list = l1;
        capacity *= 2;
    }
    list[size++]=c;//here is the exception
    return *this;
}

杂货标题为:

#include <string>
#include <iostream>
class Groceries {
    std::string product;
    int quantity;
public:
    Groceries() : product("empty"), quantity(0) {};
    Groceries(std::string s, int x) : product(s), quantity(x) {};
    Groceries(const Groceries& c);
    ~Groceries() {};
    std::string product();
    int quantity();
    void Print();
};

和主要看起来像

int main()
{
    ShoppingList L;
    (L += Groceries("bread", 5)) += Groceries("cheese", 2);
    L.Print();
//...
}
评论
  • Ken
    Ken 回复

    这些语句在运算符的主体中

    l1 = list;
    list = l1;
    

    没有道理。

    可以通过以下方式定义运算符

    ShoppingList& ShoppingList::operator+=( const Groceries& c) {
        if (size == capacity) {
            Groceries* l1 = new Groceries[capacity * 2];
            std::copy( list, list + size, l1 );
            delete [] list;
            list = l1;
            capacity *= 2;
        }
        list[size++]=c;//here is the exception
        return *this;
    }
    

    Pay attention to that you are using the same identifier product to declare different entities

    class Groceries {
        std::string product;
        //...
    public:
        //...
        std::string product();
        //...