如何访问存储在列表中的对象

时间:2012-11-15 21:20:48

标签: c++ list object

如何访问存储在列表中的对象。我不想使用向量或#include <list>。任何见解都表示赞赏。谢谢!以下是我的班级定义:

class UnsortedType  // UnsortedType.h   
{
    private:                
        int length, currentPos;
        book info[MAX_ITEMS];


    public:             
        UnsortedType();
        bool IsFull()  const ;
        int  LengthIs()  const ;  // returns length of list
        void RetrieveItem(book& item, bool& found);
        void InsertItem(book item); // adds objects to the list
        void DeleteItem(book item); // deletes objects in the list
        void ResetList(); // resets list to default length -1
        void GetNextItem(book& item); // gets the next object in the list

};

此列表中存储的是书籍对象。包含在这些对象中的是标题,作者,价格等...我的问题是如何在列表中存储每个对象后访问它们。我希望能够比较列表中存储的对象的属性。例如每本书的价格。

//main
#include <iostream>
#include "Book.h"
#include "textbook.h"
#include "Name.h"
#include "unsorted.h"

using namespace std;


int main()
{


    book b1("The Exception to the Rulers", "Amy", "Goodman", "Hyperion", 342, "1-4013-0131", 21.95,'N');
    book b2("Who moved my cheese", "Spencer", "Johnson", "Red Tree", 95, "0-399-14446-3", 19.99,  'H');
    book b3("Hellbound Hearts", "Neil", "Gaiman", "Dark Harvest", 326, "978-1-4391-4090-1", 16.00, 'F');

    UnsortedType L1; // creating a list "L1" 

    L1.InsertItem(b1); // populating the list with the first book
    L1.InsertItem(b2); // populating the list with the second book
    L1.InsertItem(b3); // populating the list with the third book


    return 0;
}

这些是book.h中的函数。

// book.h
enum RelationType
{
    LESS, EQUAL, GREATER
};

class book
{
private: 
    string title; 
    Name aurthor; 
    string publisher; 
    string ISBN; 
    int pages; 
    float price; 
    char code; 


public:
    RelationType ComparedTo(book) const;
    class negativeNumber{};
    void setTitle(string);
    void setAurthor(string f, string l);
    void setPublisher(string);
    void setISBN(string);
    void setPages(int);
    void setPrice(float);
    void setCode(char);
    string getTitle();
    Name getAurthor();
    string getPublisher();
    string getISBN();
    int getPages();
    float getPrice();
    char getCode();
    void PrintBook();
    book(); //default constructor
    book(string, string, string, string, int, string, float, char); //constructor with args
    ~book(); //Destructor
};

1 个答案:

答案 0 :(得分:1)

Book& UnsortedType::operator[](const int i))
{
  //check if array is in bounds
  return info[i];
}

这将允许您使用未排序的类L1 [3];

访问书籍对象

或者在你的情况下,这是一个访问每个对象并确定书籍最低价格的例子:

double UnsortedType::FindLow()
{
    double low = 9999;      //used to store lowest value
    for(int i = 0; i < length; i++) //loop through array
    {
        if(info[i].price < low) //if the price of this book is lower than the current lowest
            low = info[i].price;
                //set low to new low
    }
    return low;
}