开发者

C++ class containing arrays

I'm starting a C++ app project that basically has an object class as it's core to hold the data, then some functions will process that object's data to get the info required. I've written similar to this before in VB.net, and I've written small programs in C++ before, but that was back in Turbo C++ and didn't include creating my own class. I'd like to write this one in VC++, and I'm asking for some advice on structuring this class before I begin. When I've done similar in VB.net, I've used the approach of having structures and functions nested in a main structure. For example:

Public Structure struct_Tags  
    Public Structure struct_TagProps  
        Public Name As String  
        Public Value As String  
    End Structure  
    Public 开发者_开发百科TagName As String  
    Public TagProperties() As struct_TagProps  
    Public Function HasProperties() As Boolean  
        HasProperties = False  
        If Not TagProperties Is Nothing Then  
            HasProperties = True  
        End If  
    End Function  
End Structure  
Dim obj_Tags() As struct_Tags

This approach has worked fine in VB.net, and I dynamically redimension obj_Tags() and obj_Tags().TagProperties() by +1 whenever I need to within my processing loops. But my reasearch tells me that in C++ I can't have an empty array variable of the TagProperties struct in my class. Is this correct? I have no way of ever knowing what the array bounds will be in advance, so how to set this class up to have dynamically altering array bounds? By using Vector? I could have the arrays initialised with [0] bound as long as I can dynamically add dimensions to the array. Is that possible? Thanks in advance for any help.


struct struct_Tags {
    struct struct_TagProps  {
        string Name;
        string Value;
    };
    string TagName;
    vector<struct_TagProps> TagProperties;  
    bool HasProperties() const {
        return !TagProperties.empty().
    }
};
vector<struct_Tags> obj_Tags;

To insert something:

struct_Tags newValue;

struct_Tags::struct_TagProps newProps = { "my name", "my value" };
newValue.TagProperties.push_back(newProps);

obj_Tags.push_bcak(newValue);


Depends on what kind of array you need:

If you need a dynamically allocated (variable size) array, go for a std::vector.

If you need a more simple array, that cannot be resized, take a look at boost::array.


The best way to create your array is to use a std::vector. If you use the classical arrays using [] notation, you cannot resize the arrays again at runtime. You need to create a new array and copy your old array into it, then delete your old array. Anyways, it's a complicated affair, and as said by others, just use std::vector.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜