【问题标题】:Struct type "does not provide a subscript operator"结构类型“不提供下标运算符”
【发布时间】:2015-04-01 06:40:02
【问题描述】:

我正在尝试将文件中的值读取到结构数组中。但是,我不断收到编译器错误,告诉我我的结构 Books 没有提供下标运算符,我迷路了。

结构体包含在头文件中,而结构体数组的声明在 main() 中。以下是 functions.h 头文件中的(相关)代码:

#ifndef FUNCTIONS_H
#define FUNCTIONS_H
#include <iostream>
#include <string>
#include <fstream>
using namespace std;

struct Books
{
        int ISBN;
        string Author;
        string Publisher;
        int Quantity;
        double Price;
};


class functions
{
        public:
                void READ_INVENTORY(Books, int, int);

};


// Function definitions

void READ_INVENTORY(Books array, int max, int position)
{
        ifstream inputFile;
        inputFile.open("inventory.dat");

        inputFile >> array[position].ISBN;
        inputFile >> array[position].Author;
        inputFile >> array[position].Publisher;
        inputFile >> array[position].Quantity;
        inputFile >> array[position].Price;

        cout << "The following data was read from inventory.dat:\n\n"
             << "ISBN: " << array[position].ISBN << endl
             << "Author: " << array[position].Author << endl
             << "Publisher: " << array[position].Publisher << endl
             << "Quantity: " << array[position].Quantity << endl
             << "Price: " << array[position].Price << endl << endl;
}

这是 main 中的结构声明数组以及它的使用方式:

#include <iostream>
#include <string>
#include <fstream>
#include "functions.h"
using namespace std;

int main()
{
        const int MAX_SIZE = 100;
        int size, choice;
        functions bookstore;
        Books booklist[MAX_SIZE];

        cout << "Select a choice\n\n";

            cin >> choice;

            size = choice;

            switch (choice)
            {
                    case 1: bookstore.READ_INVENTORY(booklist[choice], MAX_SIZE, size);
                            break;

             }
}

编译后,我收到 10 条错误消息(每次使用 array[position] 时有一条):error: type 'Books' does not provide a subscript operator

【问题讨论】:

  • Books array 不是数组。你应该通过Books* array。目前你只通过一本书,显然没有 []。顺便说一句,你应该改进变量名,数组不是很有描述性; books 怎么样?
  • array 不是数组...

标签: c++ arrays struct header-files subscript-operator


【解决方案1】:

你的代码有太多问题,你把READ_INVENTORY定义为一个全局函数。因此,您可能已经收到对functions::READ_INVENTORY 的未定义引用。另一个问题是你传递了Books 而不是Books*,所以你不能使用[] 运算符。

改变这个

void READ_INVENTORY(Books array, int max, int position) 
{

void functions::READ_INVENTORY(Books* array, int max, int position)
{

现在我们已经改变了参数类型,改变这一行

case 1: bookstore.READ_INVENTORY(booklist[choice], MAX_SIZE, size);

case 1: bookstore.READ_INVENTORY(booklist, MAX_SIZE, size);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-21
    • 2013-01-21
    • 1970-01-01
    • 2022-07-04
    • 1970-01-01
    • 2018-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多