Re: How to initialize an array of class?

zhanglr wrote:

Is it possible to initialize an array of class which don't provide a no-arg constructor?

I just write few lines code to explain what I want.

I have a class call _CString. (I will use it as a sealed class. so I can create and use an array of _CString.) and "_CString arstr[10]" is a member variable of CStrArray.

I hope to initialize arstr at CStrArray's constructor like "CStrArray( const char* arpch[10] ): arstr(arpch){};" but it failed. So I have to provide "_CString()" and "void SetData(const char* pch)"

Yes, you can't copy arrays.

I don't really appreciate this way. But I don't know what I can do to solve this kind of problem. or what is the normal way to handle this kind of issue (convert an input array in c style, e.g. const char*[], to c++ style array e.g. _CString[] or _CString&[])?

Generally you have to copy the values one by one, but the best alternative is to use a templated container class, like std::vector.

#include <string>
#include <vector>

class CStrArray
  CStrArray( const char* arpch[10] )
    :arstr(arpch, arpch + 10) //initialize from range
  typedef std::vector<std::string> arstr_t;
  arstr_t arstr;

And that's it. You can even work with arbitrary lengths:
  template <int N>
  CStrArray( const char* arpch[N] )
    :arstr(arpch, arpch + N) //initialize from range