简体   繁体   English

访问在 header 文件 C++ (非全局)中声明的向量

[英]Accessing vectors declared in header file C++ (not global)

I've submitted an assignment which has met all the criteria except that I'm not allowed to have global variables except if they're constants, and I had my vector set up as a global variable.我已经提交了一个满足所有标准的作业,除了我不允许使用全局变量,除非它们是常量,并且我将我的向量设置为全局变量。

I'm now finding it impossible to have my vector used in my header file as well as my class functions file and my main class file.我现在发现不可能在我的 header 文件以及我的 class 函数文件和我的主要 class 文件中使用我的向量。

I have a primary class and a derived class, and the vector items are of the derived class.我有一个主要的 class 和一个派生的 class,向量项是派生的 class。 I've put my vector definition in the header now in the primary class:我已经把我的向量定义放在 header 现在放在主要的 class 中:

vector<Stock> arrStock;

But when trying to add objects into the vector from the input file and subsequently perform actions on it, I am able to either set up the functions inside the classes functions class, OR call the functions I've set up in the main class (if I have the functions set up as static).但是当尝试将对象从输入文件添加到向量中并随后对其执行操作时,我可以在类函数 class 中设置函数,或者调用我在主 class 中设置的函数(如果我将功能设置为静态)。

What am I doing wrong?我究竟做错了什么? Currently with the way the code has been set up, I'm having error E0245 "a nonstatic member reference must be relative to a specific object" on all the functions that I'm calling in my main class.目前,按照代码的设置方式,我在主 class 中调用的所有函数都出现错误 E0245“非静态成员引用必须相对于特定对象”。 It's probably worth noting that when I had the vector set up as a global variable, the functions were defined as static and they worked perfectly, so I'm open to the fact that they need to be static and that my issue is with the application of the array in the Assignment2_classes.cpp file instead.可能值得注意的是,当我将向量设置为全局变量时,这些函数被定义为 static 并且它们运行良好,所以我愿意接受它们需要是 static 并且我的问题与应用程序有关的事实Assignment2_classes.cpp 文件中的数组。

Please see my code snippets below:请在下面查看我的代码片段:

Assignment2.h:作业2.h:

class Product 
{

private:
    string  title, surname;
    long long int isbn;
    double  wholesalePrice;

public:
    string getTitle();
    string getSurname();
    long long int getIsbn();
    double getWholesalePrice();

    void setTitle(string);
    void setSurname(string);
    void setIsbn(long long int);
    void setWholesalePrice(double);
    
    Product();
    ~Product();
    Product(string, string, long long int, double);

    void importProducts();
    void newProduct();
    void delProduct();
    void runReport();
    void checkStock();
    void clrStock();

    vector<Stock> arrStock;
};

// creating the derived class Stock
class Stock :public Product 
{

public:
    double retailPrice;
    char bookFormat;
    int stockLevel;

    double getRetailPrice();
    char getBookFormat();
    int getStockLevel();
    
    void setRetailPrice(double);
    void setBookFormat(char);
    void setStockLevel(int);

    Stock();
    ~Stock();
    Stock(string, int, char, string, double, long long int, double);
    
    void setStockInfo(long long int, string, string, double, int, double, char);
    
};

Assignment2_classes.cpp:分配2_classes.cpp:

void Product::importProducts()
{
    // code adapted from: https://stackoverflow.com/questions/16878259/how-to-read-in-a-set-of-values-from-a-text-file-then-go-to-the-next-line-and-do
    // telling the function which input file it is reading from
    ifstream productsFile("products_v5.txt");
    
    // creating local variables
    Stock aStock;
    double tempRetailPrice = 0;
    string undsc = "_";
    string space = " ";
    size_t position;


    std::cout << "Importing books...\n";
    
    // reading the books into an array
    while (productsFile >> aStock.title >> aStock.stockLevel >> aStock.bookFormat >> aStock.surname >> aStock.wholesalePrice >> aStock.isbn)
    {
        // replacing the underscores in the title names with spaces so the output looks better
        // code adapted from https://www.educba.com/c-plus-plus-replace/
        while ((position = aStock.title.find(undsc)) != string::npos)
        {
            aStock.title.replace(position, 1, space);
        }
        
        // calculating the retail prices of the books depending on their format
        switch (aStock.bookFormat)
        {
        case 'a': tempRetailPrice = aStock.wholesalePrice * 1.43;
            break;
        case 'e': tempRetailPrice = aStock.wholesalePrice * 1.08;
            break;
        case 'h': tempRetailPrice = aStock.wholesalePrice * 1.45;
            break;
        case 's': tempRetailPrice = aStock.wholesalePrice * 1.27;
            break;
        }
        aStock.setRetailPrice(tempRetailPrice);
        arrStock.push_back(aStock);
    }

    // letting the user know how many books have been added and how many books are currently in the array
    std::cout << "\n" << to_string(arrStock.size()) << " books have been added.\n";
    std::cout << "\nBiblioden Books currently has " << to_string(arrStock.size()) << " different books.\n";
}

Assignment2_main.cpp:分配2_main.cpp:

int main()
{

    char createBook;
    char deleteBook;
    char viewReport;
    char checkOrders;

    // creating the heading of the output
    cout << "-----------------------------------------------------------------------------------------\n" << "  Biblioden Systems\n" << "-----------------------------------------------------------------------------------------\n";
    
    ifstream productsFile("products_v5.txt");
    
    // checking whether the file is open and gracefully exiting if it can't be opened
    if (!productsFile.is_open())
    {
        cout << "\nCannot open file.\n";
        return 1;
    }
    Product::importProducts();
    
    //closing the file
    productsFile.close();
    
    cout << "\nWould you like to enter a new book? (Y/N): ";
    cin >> createBook;
    if (createBook == 'Y' || createBook == 'y')
    {
        Product::newProduct();
    }

    cout << "\nWould you like to delete a book? (Y/N) ";
    cin >> deleteBook;

    if (deleteBook == 'Y' || deleteBook == 'y')
    {
        Product::delProduct();
    }

    cout << "\nWould you like to view a report? (Y/N) ";
    cin >> viewReport;
    if (viewReport == 'Y' || viewReport == 'y')
    {
        ofstream report("report.txt");

        // checking whether the file is open and gracefully exiting if it can't be opened
        if (!report.is_open())
        {
            cout << "\nCannot open file.\n";
            return 1;
        }
        else
        {
            Product::runReport();
            
            // closing the file
            report.close();
        }
    }

    cout << "\nWould you like to check the order list against the stock list? (Y/N) ";
    cin >> checkOrders;
    if (checkOrders == 'Y' || checkOrders == 'y')
    {
        ifstream ordersFile("orders_v5.txt");

        // checking whether the file is open and gracefully exiting if it can't be opened
        if (!ordersFile.is_open())
        {
            cout << "\nCannot open file.\n";
            return 1;
        }
        else
        {
            Product::checkStock();
            // closing the file
            ordersFile.close();
        }
    }

    // clearing out the array once the user is finished with it
    Product::clrStock();
    return 0;
}

As mentioned in comments, the call Product::importProducts();如评论中所述,调用Product::importProducts(); requires importProducts() to be a static member function of Product .要求importProducts()Productstatic成员 function 。

In your case, you can't declare it as static (and it doesn't make sense to do so) since you use (non-static) class members inside the function.在您的情况下,您不能将其声明为static (这样做没有意义),因为您在 ZC1C425268E68385D1AB5074C17A94F1 中使用(非静态)class 成员。

You need an instance of Product to call the member functions on.您需要一个Product实例来调用成员函数。
For example:例如:

Product p;          // Create an instance of Product
p.importProducts(); // Call importProducts() from (and for) the previously created instance

On the other hand, if you don't want to create any instance of Product and thus you want a unique vector for the whole program, you may mark your members (and members functions) static to solve your issue.另一方面,如果您不想创建Product的任何实例,因此您想要整个程序的唯一向量,您可以标记您的成员(和成员函数) static来解决您的问题。

The declaration of your member variable arrStock comes before the class Stock is declared.成员变量arrStock的声明在 class Stock 声明之前。 You cannot reference a class that has not been declared yet.您不能引用尚未声明的 class。 You have to make your vector as a vector of pointer (or shared_ptr) then you can forward declare the class, before declaring Product, with:您必须将向量设为指针向量(或 shared_ptr),然后您可以在声明 Product 之前转发声明 class,其中:

class Stock;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM