开发者

Dynamic Array in a class

开发者 https://www.devze.com 2023-02-26 06:21 出处:网络
I have been looking around for a while trying to under stand how to have a class, then how to also have a dynamic array in it.

I have been looking around for a while trying to under stand how to have a class, then how to also have a dynamic array in it.

I am trying to build a bank account c++ program that will make a unlimited number of accounts (memo开发者_如何学JAVAry is the only limit), so i want a dynamic array, where say, p[1] is the first account then p[2] is the second account and and to have it be a member of the bankAccount class. So that i can have the array at memory location 1, aka account number 1, and then also have other info like first last name, balance and etc associated with it. maybe something like if i have array p[] in class bankAccount,then i can use p[1].name.

I am new to this site, if there are better ways to ask questions or post code examples, please feel free to tell me.

This is the main part that i am having trouble with, declaring the dynamic array as a member of the class:

class bankAccount
{
    int i;
    int index;
    int AccountNum;
    double balance;
    string last;
    string first;
public:
    void intro();
    void deposit();
    void withdraw();
    void newAcc ();
    void editAcc();
    void chgAcc();
    void print();
    bankAccount::bankAccount();
}p [10]; // This is what i want to be dynamic

Thank you.


I think that the data structure that you are looking for is std::vector. A std::vector is basically a dynamic array under the hood but everything is managed for you.

I would actually go so far as to say that you should never use a dynamic array in C++, it is what I would class as a C concept that has been superseded. (All rules have their exceptions, but what I mean is that unless you know why you are choosing a dynamic array over a vector, then you should choose a vector.


It seems like you are trying to implement dynamic array by yourself, looking at this piece of code:

 bankAccount *p; 

C++ STL already has dynamic array implemented, which is std::vector.


You allocated backAccount[i] when I was 1. When you create a new account you would need to free this are reallocate. Also you life will be allot easier if you sue std::vector.

0

精彩评论

暂无评论...
验证码 换一张
取 消