我正在做一个数据结构练习,从昨天开始我就因为总线错误而被阻塞,我认为这是因为我正在用内存做坏事。但我不知道到底是什么。
以下是我对这一做法提出的要求:
这是我的密码。对于var名称表示歉意,我必须用西班牙语来做,因此名称是西班牙语的。
class producto { // My product
public:
string marca;
double precio;
int visitas;
int compras;
producto () {}
producto (string M, double P, int V = 0, int C = 0) : marca(M), precio(P), visitas(V), compras(C) {}
};
class nodo {
public:
producto valor; // value
nodo *siguiente; // next
nodo *anterior; // prev
nodo (producto P, nodo *A = NULL, nodo *S = NULL) : valor(P), anterior(A), siguiente(S) {}
};
class lista {
private:
nodo *inicio;
nodo *final;
nodo *actual;
public:
lista();
bool esta_vacia(); // is empty?
bool es_final(); // is the end?
int insertar(producto p); // insert given p
void moverPrincipio(); // "move to beginning"
void siguiente(); // "next"
void imprimir(); // "print"
int leer(producto *p); // read, return 0 or 1 if successful, return product by ref
};
lista::lista() {
this->inicio = NULL;
this->final = NULL;
this->actual = NULL;
}
bool lista::esta_vacia() {
return (this->inicio == NULL);
}
bool lista::es_final() {
return (this->actual == NULL);
}
void lista::moverPrincipio() {
this->actual = this->inicio;
}
void lista::siguiente() {
if(!this->es_final()) {
this->actual = this->actual->siguiente;
}
}
void lista::imprimir() {
int i = 1;
producto *p;
this->moverPrincipio();
while(!this->es_final()) {
if(this->leer(p) == 0) {
cout << i << ".- ##" << p->marca << "##, Views ##" << p->visitas << "##\n";
p->visitas++;
i++;
this->siguiente();
}
}
}
int lista::leer(producto *p) {
if(this->actual != NULL) {
*p = this->actual->valor;
return 0;
} else {
return 1;
}
}
int lista::insertar(producto p) {
if(this->esta_vacia()) {
nodo *tmp = new nodo(p);
this->inicio = tmp;
this->final = this->inicio;
} else {
nodo *tmp = new nodo(p, this->final);
this->final->siguiente = tmp;
this->final = tmp;
}
return 0;
}我已经删除了不必要的代码。这就是我使用它的方式(不幸地失败了):
lista *productos = new lista();
productos->insertar(producto("Shoes", 19.90));
productos->insertar(producto("Socks", 25.00));
// I should expect views = 0
productos->imprimir();
// But now, views = 1
productos->imprimir();在执行时,我唯一得到的是“总线错误:第一次执行imprimir ("print")时的10”。插入工作没有错误(但也可能有问题)。
我的想法是将产品保存在节点中,并在返回它时引用它的位置,以便在那里也反映任何更改(例如,增加检索元素的视图或购买计数器,反映稍后读取列表时的更改)。
如果有人能指出我在这里所犯的错误,我会非常感激的。
谢谢!!
更新 下面是一个可编译的示例.
发布于 2014-12-06 12:27:16
您传递一个指向lista::leer的指针,并且希望向它写入一个值。您将在未分配的内存中写入。可能,您想要的是指向actual元素的指针。
首先,您需要修改签名:
int lista::leer(producto **p);注意双星,因为我们将写入指针本身。
然后,您必须在actual->valor中指定一个指向lista::leer的指针。
*p = &(this->actual->valor);最后,必须在p中传递指向lista::imprimir的指针。
if(this->leer(&p) == 0) {
// ...
}或者,您可以修改lista::leer以返回一个指针,并检查它是否为nullptr/NULL。
https://stackoverflow.com/questions/27331469
复制相似问题