C++ Trouble Inputting Data into Private Vector (invalid use)

前端 未结 3 450
梦如初夏
梦如初夏 2021-01-26 00:24

I have a vector of class \"Account\". It\'s private to a class BankingSystem. Here\'s how I have them defined.

Account Class:

struct newAccount
{
string          


        
相关标签:
3条回答
  • 2021-01-26 01:02

    The method is static, so it has no "this" pointer, so it has no idea what object you want to access the accounts_ variable of. Also, you will never see that printout on createAccount() because it's after the return call.

    0 讨论(0)
  • 2021-01-26 01:05

    A static method does not have access to a class instance (no this) so inside of storeAccount and addAccount the member accounts_ does not exist.

    FYI: nothing after a return statement will be executed so the line cout << "\n\t Account ID: " << a.accountID << " added successfully."; is rather useless in your current code.

    Consider the following implementation for reference:

    using namespace std;
    
    class Account
    {
    private: // data members
        string firstName;
        string lastName;
        string accountPass;
        int accountID;
        float accountBalance;
    
    public:
        // constructor that initializes members
        Account(int id, float bal, const string& fname, const string& lname, const string& pass)
            : accountID(id), accountBalance(bal), firstName(fname), lastName(lname), accountPass(pass) {}
    
    }; //end of class Account
    
    class BankingSystem
    {
    private: // data members
        int accountID;
        char fileName;
        vector<Account> accounts_;
    
    public:
        void addAccount()
        {
            int ID;
            float balance;
            string pass, first, last;
    
            // prompt input, initialize values, etc
    
                // construct a new Account from values and add it to vector
            accounts_.push_back(Account(ID, balance, first, last, pass));
        }
        void storeAccount( const Account& newAccount )
        {
                // add an already initialized account
            accounts_.push_back(newAccount);
        }
    
    
    }; // end of class BankingSystem
    
    0 讨论(0)
  • 2021-01-26 01:16

    A static member function doesn't have any special access to member variables like accounts_.

    addAccount and storeAccount are static member functions. You must have made them so for a reason but it was a mistake. Remove that static and you will remove this error. I'm guessing you'll then have a different problem. If so ask another question and find out the right way to solve that.

    0 讨论(0)
提交回复
热议问题