【问题标题】:Array of pointers to nodes not declared in scope指向未在范围内声明的节点的指针数组
【发布时间】:2014-04-20 06:18:59
【问题描述】:

我正在尝试将一个节点分配给一个指针数组中的指针,但它一直告诉我我的数组未在范围内声明。我完全不知道如何或为什么任何帮助都会大有裨益!感谢您抽出宝贵时间回复!

#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;
        }
    }
};

【问题讨论】:

  • 在 C++ 中,如果您在大括号 { ..... } 内的函数中声明变量,则在 } 之后将不再存在。

标签: c++ arrays scope


【解决方案1】:

您的指针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]
    ....

请注意,您的类正在尝试管理动态分配的资源,因此您需要注意复制构造函数和赋值运算符(要么使类不可复制和不可分配,要么实现它们。默认值不是可以接受。见the rule of three。)如果你真的在使用动态分配的指针数组,那么你也需要修复你的析构函数。目前只删除数组,不删除其中指针指向的对象。

更好的解决方案是使用一个为您管理资源并具有所需语义的类。让每个类处理单一职责更容易。

【讨论】:

  • @user3553272 很高兴它有帮助。你可以选择这个答案(除非你想先等待可能的其他答案),它甚至会给你一些代表点。请参阅here 了解更多信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-04
  • 2021-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多