【发布时间】:2017-05-16 14:21:17
【问题描述】:
!!注意:我在回答后多次编辑问题。但是下面的问题是第一个问题,第一个答案是一个有用的答案。请不要被某些cmets混淆。它们是在我多次更改问题后写的。
我有一个 Shop 模板类和 Cookie 类。 Shop 是一个保存名为 cookieShop 的 cookie 的列表。 Shop cotr 可以接受一个 cookie 作为参数,可以通过 Shop 模板类的 Add 方法添加更多。
我正在创建两个 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) 时,它会给出以下几行:
- 巧克力曲奇 50 180
- 蛋糕混合饼干 60 200 分段错误(核心转储) 为什么我会收到分段错误错误?
注意:我是 stackoverflow 的新手。如果我有错误的行为。请告诉:)
【问题讨论】:
-
您忘记在
Add中注释掉size++;。 -
@NathanOliver。因为我想打印列表[1]。我认为问题不在于。是吗?
-
谁教你原始数组是一个有用的容器是大错特错。在这里使用
std::vector你会好多了 -
这是一个家庭作业。我必须这样做。截止日期已经结束。不幸的是,我按上述方式发送了作业。不过现在想学。
-
我为您学习的愿望鼓掌,但是 1)请不要以完全改变它们的方式编辑您的问题,以及 2)当您编写代码时,最好从小而简单的东西开始可以完美运行,当您在此处发布代码时,最好将其缩减为产生错误的最小、最简单的代码。
标签: c++ template-classes