在我的模板类示例中,发生“分段错误(核心转储)”错误
In my template class example, “segmentation fault (core dumped)” error occurs
在我的代码中,我想创建一个cookie,并通过将cookie作为参数发送到shop构造函数来将其添加到商店中。它添加了 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;
}
商店:
#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<<
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 我是如何在这段代码中出现分段错误的
- 创建结构的数组时遇到分段错误
- 为什么我使用 std::copy() 收到运行时错误(分段错误)?
- 为什么我的代码包含错误分段错误(核心转储)?
- 为什么会出现此错误?- 分段错误(核心转储)
- 意外的运行时错误(分段错误)
- C++将文本文件读入数组,运行错误:分段错误
- mmap 错误:分段错误/指针无效错误
- 在我的代码中找不到错误....分段错误
- c++字符串流转换错误:分段错误
- 为什么我的代码显示错误分段错误(核心转储)