在我的代码中,我想创建一个 cookie 并将其添加到商店,方法是将 cookie 作为参数发送到 shop 构造函数。它添加了 cookie,但给出了分段错误错误。
我得到结果:
- Chocolate Cookie 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;
}
商店.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;
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
饼干.h:
#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
Cookie.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;
}