在我的模板 class 示例中,即使我没有定义 add 方法,它也会添加 take "segmentation fault (core dumped)" 错误

In my template class example, Even if I dont define add method, it addstake "segmentation fault (core dumped)" error

!!注意:我在回答后多次编辑问题。但是下面的问题是第一个问题,第一个答案是一个有用的答案。请不要被一些评论混淆。改了很多次问题后写的


我有一个商店模板 class 和 class Cookie。 Shop 是一个保存名为 cookieShop 的 cookie 的列表。 Shop cotr可以取一个cookie作为参数,更多的可以通过Shop模板的Add方法添加class.

我正在创建两个 cookie。一是shop cotr添加,二是add方法。即使我不在 add 方法中编写代码,第二个 cookie 也会添加到商店列表中。我试图理解它为什么这样做但无法理解。

这是我的代码:

//Shop.h

#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;
    string name;
    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 = &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

//Cookie.h

#ifndef COOKIE
#define COOKIE
#include <string>
using namespace std;

class Cookie{
    string name;
    int piece;
    float price;
public:
    Cookie();
    Cookie(string n, int pi, float pr);
    friend ostream& operator<<(ostream& out, const Cookie& C);
};

#endif

//Cookie.cpp

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

Cookie::Cookie() {}
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;
}

//main.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 <<endl;


    return 0;
}

如您所见,Add 方法中的代码已被注释。它如何添加第二个 cookie?

编译时 (gcc main.cpp Cookie.cpp) 和 运行 它 (./a.out) 它给出以下行:

  1. 巧克力曲奇 50 180
  2. 蛋糕混合饼干 60 200 分段错误(核心已转储) 为什么我会收到分段错误?

注意:我是 Whosebug 的新手。如果我有错误的行为。请告诉:)

这里:

template<class type>
Shop<type>::Shop(type t) : size(0){
  list = new type;
  list = &t;
  size++;
}

变量 t 是该函数的局部变量。您使 list 成为指向该变量的指针。当函数终止时,变量超出范围,Shop 留下一个悬挂指针,你会得到未定义的行为。