[英]Array of pointers to nodes not declared in scope
我正在嘗試將一個節點分配給指針數組的指針,但它一直告訴我我的數組未在范圍內聲明。 我完全不知道如何或為什么這樣任何幫助都會非常有益! 感謝您抽出寶貴時間作出回應!
#include <iostream>
#include "book.h"
using namespace std;
class bookstore
{
private:
int amount = 5;
int counting = 0;
public:
bookstore()
{
bookstore *store;
store = new book*[amount];
for(int i = 0; i < amount; i++)
{
store[i] = NULL;
}
}
~bookstore(){ delete[] store; }
void addbook(string a,string b, string c, string d, string e)
{
if (counting == amount)
{
cout<<"Full House!"<<endl;
return;
}
store[counting] = new book(a,b,c,d,e);
counting++;
}
void print()
{
for(int i = 0; i < amount; i++)
{
cout<<store[i]->name<<" "<<store[i]->publisher<<" "<<store[i]->year<<" "<<store[i]->price<<" "<<store[i]->category<<endl;
}
}
};
指針store
是默認構造函數的本地store
。 看起來你是在追蹤數據成員。 此外,你似乎是在一系列指針之后。 如果是這樣,您需要bookstore
成為指針的指針:
class bookstore
{
private:
bookstore** store; // or bookstore* store
int amount = 5;
int counting = 0;
並修復構造函數以使用它:
bookstore()
{
store = new book*[amount]; // or store = new book[amount]
....
請注意,您的類正在嘗試管理動態分配的資源,因此您需要處理復制構造函數和賦值運算符(使該類不可復制且不可分配,或實現它們。默認值是不可接受的。請參閱規則三 。)如果你真的使用動態分配的指針數組,那么你也需要修復你的析構函數。 目前,它只刪除數組,但不刪除其中指針指向的對象。
更好的解決方案是使用一個為您管理資源的類,並具有所需的語義。 讓每個班級處理一項責任更容易。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.