在我的模板类示例中,发生“分段错误(核心转储)”错误

In my template class example, “segmentation fault (core dumped)” error occurs

本文关键字:错误 分段错误 分段 核心 转储 发生 我的      更新时间:2023-10-16

在我的代码中,我想创建一个cookie,并通过将cookie作为参数发送到shop构造函数来将其添加到商店中。它添加了 cookie,但给出了分段错误错误。

我得到的结果:

  1. 巧克力曲奇 50 180
    分段错误(核心转储(!

找不到我错误的代码部分。你能帮忙吗?

主.cpp:

#include <iostream>
#include <string>
#include "Shop.h"
#include "Cookie.h"
using namespace std;

int main(){
    Cookie cookie1("Chocolate Cookie", 50, 180);
    Cookie cookie2("Cake Mix Cookie", 60, 200);
    Shop<Cookie> cookieShop(cookie1);
    //cookieShop.Add(cookie2);
    cout << cookieShop ;
    return 0;
}

商店:

#ifndef SHOP_T
#define SHOP_T
#include <string>
using namespace std;
template<class type>
class Shop;
template<typename type>
ostream& operator<<(ostream& out, const Shop<type>& S){
    for(int i = 0; i < S.size; i++)
        out << i + 1 << ".t" << S.list[i] << endl;
}
template<class type>
class Shop{
    type *list;
    int size;
public:
    Shop() { list = 0; size = 0; }
    Shop(type t);
    ~Shop(){ delete[] list; }
    void Add(type A);
    friend ostream& operator<< <>(ostream& out, const Shop<type>& S);
};
template<class type>
Shop<type>::Shop(type t) : size(0){
    list = new type();
    list[0] = t;
    size++;
}
template<class type>
void Shop<type>::Add(type A){
    type *temp = new type[size+1];
    for(int i = 0; i < size; i++)
        temp[i] = list[i];
    delete[] list;
    temp[size] = A;
    list = temp;
    size++;
}
#endif

饼干:

#ifndef COOKIE
#define COOKIE
#include <string>
using namespace std;
class Cookie{
    string name;
    int piece;
    float price;
public:
    Cookie(string = "", int = 0, float = 0);
    friend ostream& operator<<(ostream& out, const Cookie& C);
};
#endif

饼干.cpp:

#include "Cookie.h"
#include <iostream>
#include <string>
using namespace std;
Cookie::Cookie(string n, int pi, float pr){
      name = n;
      piece = pi;
      price = pr;
}
ostream& operator<<(ostream& o, const Cookie& C){
    o << C.name << "t" << C.piece << "t" << C.price;
}

您忘记在两个operator<<函数中返回 ostream。这会导致链接<<操作时出现未定义的行为。

例如,它等效于:

o.operator<<(C.name).operator<<("t")

其中o.operator<<(C.name)具有未定义的返回值,导致无效引用的下一个.operator<<