質問

I am working on an assignment in C++, a language I am not particularly proficient in.

I am attempting to declare a dynamic array of 'Account' objects in a file main.cpp:

Account * acctArray = new Account[];

main.cpp includes Account.h:

class Account {
private:
    int customerID;
    int BSB;
    int acctNumber;
    string surname;
    string firstName;
    double balance;
    double withdrawn;
public:
    Account() {};
    //setters
    void setCustID(int ID);
    void setBSB(int inBSB);
    void setAcctNo(int number);
    void setSurname(string sname);
    void setFirstName(string fname);
    void setBalance(double bal);
    void setWithdrawn(double withd);
    //getters
    //(snipped for irrelevance)
    //methods
    bool withdraw(double amount);
};

However, when compiling on my uni's unix machine (the machine the assignment must be submitted on), I get the following error:

"main.cpp", line 130: Error: The type "Account[]" is incomplete.

I tried compiling with

Account * acctArray = new Account[5];

to see if I could isolate the problem, and this line compiled fine.

What am I doing wrong?? I fear the solution lies in pointers/references and my lack of understanding thereof.

役に立ちましたか?

解決

An array in C++ has a fixed size. There is no built-in "dynamic array" functionality. If you want a dynamic array, use a std::vector<Account>.

I am working on an assignment in C++, a language I am not particularly proficient in.

It is best to avoid new and explicit dynamic allocation wherever possible. If you think you need to dynamically allocate something using new and manage it yourself, there's probably a better way to accomplish the task.

他のヒント

C++ is kind of confusing when it comes to objects. One thing to keep in mind when dealing with objects is that you will almost always want them to be pointers, specifically for this purpose. This is what new Account does; it returns a pointer to an account, rather than an account itself. Additionally, you will want your array to be a separate pointer. Therefore, what you want to do is make a double pointer.

This is actually pretty simple. When you are instantiating your array of objects, all you have to do is this: Account **acounts = new Account*

I created a small piece of sample code that demonstrates this, and it lets you create an arbitrary number of objects in an array. You can view and play with the code here on codepad.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top