开发者

C++ Array of Objects

I have an array in a class that should hold some instances of other objects. The header file looks like this:

class Document {
private:
    long arraysize;
    long count;
    Row* rows;
public:
    Document();
    ~Document();
}

Then in the constructor I initialize the array like this:

this->rows = new Row[arraysize];

But f开发者_运维百科or some reason this just sets rows to an instance of Row rather than an array of rows. How would I initialize an array of Row objects?


Both SharpTooth and Wok's answers are correct.

I would add that if you are already struggling at this level you may be better off using a std::vector instead of a built-in array in this case. The vector will handle growing and shrinking transparently.


This should work. One possible "error" would be an incorrect value for arraySize.

However you should better use a std::vector from the standard library for that purpose.

#include <vector>
class Document { 
    // ...
    std::vector<Row> rows;
    // ...
};

and in your constructor:

Document::Document() : rows(arraySize) { // ... }

or

Document::Document() { rows.assign(arraySize, Row()); }


If arraySize contains a reasonable value at that point you actually get an array. I guess you trust your debugger and the debugger only shows the 0th element (that's how debuggers treat pointers), so you think there's only one object behind that pointer.


For i in [0;arraysize[, *(this->rows+i) should be an instance of row.


What precisely makes you think that rows is only one element? Make certain that you arraysize isn't 1. If it is, you'll get an array of 1 element. Mind you, you must still call delete [] with an array of size 1.

Also, why is arraysize different than count? Using that terminology, you should be making an array of count elements and arraysize should be equal to sizeof(Row) * count.

Also, you specifically ask "How would I initialize an array of Row objects?". Do you mean allocate? If so, that's how you would do so. If you mean initialize, the default constructor of Row will be called on each element of the array when the array is allocated.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜