简体   繁体   中英

Use constructor from a class in another one to allocate an array with new

I don't know (if it's even possible) how to allocate an array from a class that has constructor with parameters using another constructor with parameters. For example (I'll write just what's actually relevant. Uhm, I doubt the template is, but still):

template <typename T>
class C1 {
    T *array; 
    public:
        C1 (int n) {
            array = new T [n];
        };
};

class C2 {
    int length;
    int lengthArrayC1;
    C1<T> *array;
    public:
        C2 (int x, int y) {
            length = x;
            lengthArrayC1 = y;
            array = //and here's where I'm lost
        };
};

I tried writing something like this in many ways:

array = new [length] C1<T> (lengthArrayC1);

but none worked.

Can't do it: Object array initialization without default constructor

A type must have a no-argument constructor in order for you to new[] an array of it. But, see the tip in the answer to that question about using std::vector , which allows you to specify a prototype object to use for initializing the array elements.

** Caveat, I don't have a C++ compiler at this moment, so there might be some syntax errors in my response. With that said, the idea still holds. **

Change your C1 so that it uses partial template specialization (note the second specialized argument)...

template <typename T, size_t default_size>
class C1 {
    T *array; 
    public:
        C1 (int n = default_size) {
            array = new T [n];
        };
};

... then you can do the following:

array = new [length] C1<T, lengthArrayC1>;

If you cannot modify C1 (because the code is owned by someone else... it happens), then you could do the following:

template <typename T, size_t default_size>
class MyC : public C1
{
public:
   MyC() : C1(default_size){}
};

...

array = new [length] MyC<lengthArrayC1>;

Making a new class just to do that is ugly, but sometimes it is the only way to get things going if we really have a need to the thing you are trying to do in your original question .

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM