簡體   English   中英

結構類型“不提供下標運算符”

[英]Struct type “does not provide a subscript operator”

我試圖從文件中讀取值到結構數組。 但是,我不斷收到編譯器錯誤,告訴我我的struct,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中的struct聲明數組及其使用方式:

#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條錯誤消息(每次使用一個數組[position]時)狀態: 錯誤:類型'Books'不提供下標運算符

您的代碼中存在太多問題,您將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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM