user4340939
user4340939

Reputation:

vector as with class objects in another class

I can start wit hsaying that I'm kind of new to programming. I got an assigment to create first a class bank account that holds one singel bank account, and also a class Bank that holds all bankaccounts in a vector or array. One method that had to be included was that it should print out all the accounts in a specific Bank vector.

What I don't understand is what arguments I should pass in to such a method and also how do I call it from the main function where the vector is created.

This is what I've got so far:

void skriv_kontolista(vector <Konto>& nyttKonto)
{
    for (unsigned int i = 0; i < nyttKonto.size(); i++)
    {
    cout << "Konto: " << i << endl;
    cout << "Innehavarens kontonummer: " << nyttKonto[i].nummer << endl;
    cout << "Innehavarens namn: " << nyttKonto[i].innehavare << endl;
    cout << "Innehavarens saldo: " << nyttKonto[i].saldo << endl;
    cout << "Innehavarens r\x84ntesats: " << nyttKonto[i].rantesats << endl;
    }
}    

Is that the right way to do it, and if so, how do I call this method from my main function?

Sorry if my english is bad, it's not my native language.

Thanks in advance.

Upvotes: 1

Views: 156

Answers (1)

anatolyg
anatolyg

Reputation: 28300

The code looks OK; it should work. However, this

One method that had to be included was that it should print out all the accounts in a specific Bank vector.

leads me to believe that skriv_kontolista should be a method in class Bank. Your skriv_kontolista function looks like it's not a method in class Bank (but I don't know for sure).

If indeed it should be a method of class Bank, you should have it in your code like this:

class Bank
{
    ...
    void skriv_kontolista(vector <Konto>& nyttKonto)
    {
        ...
    }
    ...
}

In addition, a method has access to all the fields of the class. One of the fields is the vector that the method must print, so there is no need to send it as a parameter to the function!

class Bank
{
    void skriv_kontolista() // no need to have any parameters
    {
        ...
        cout << "Innehavarens namn: " << nyttKonto[i].innehavare << endl;
        ...
    }

    vector <Konto>& nyttKonto; // a field of the class
}

How to call it from the main function:

int main()
{
    Bank bank1, bank2, bank3;
    ...
    bank1.skriv_kontolista();
    bank2.skriv_kontolista();
    bank3.skriv_kontolista();
}

Upvotes: 1

Related Questions